【问题标题】:draw lines around the image from the centroid从质心在图像周围画线
【发布时间】:2021-08-25 03:45:04
【问题描述】:

原图circle

设置图片

import cv2
import numpy as np
import matplotlib.pyplot as plt
image = cv2.imread('blackcirr.jpg')
fig = plt.figure(figsize = (5, 5))
plt.imshow(image)

寻找质心

gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
canny_edges = cv2.Canny(gray_img, 30, 200)
M = cv2.moments(canny_edges)
#calculate x,y coordinate of the center
cx = int(M['m10'] / M['m00'])
cy = int(M['m01'] / M['m00'])

circle = cv2.circle(image, (cx,cy), 5, (255,255,0), -1)
cv2.putText(image, "centroid", (cx -25, cy-25), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,0),)
fig = plt.figure(figsize = (5, 5))
line = cv2.line(image,(cx,cy), () )
plt.imshow(image)
plt.xticks([])
plt.yticks([])

我想每隔 2 度或设定的度数绘制一条线,将质心连接到形状中的点。

Wanted Result

【问题讨论】:

    标签: python python-3.x opencv


    【解决方案1】:

    我认为没有必要使用 Canny 边缘检测算法来找到圆的质心,一个简单的索引就可以了。

    import cv2
    import numpy as np
    from math import ceil, sin, cos, pi
    from matplotlib import pyplot as plt
    
    img = cv2.imread('circle.jpg', 0)
    r, c = round(img.shape[0]/2), round(img.shape[1]/2)  # center row, center column
    diameter = len([i for i in img[r, :] if not i])  # Count the black (circle) pixels from the middle
    radius = ceil(diameter/2)
    
    spacing = 0.5  # Can manually adjust for desired spacing
    thetas = np.arange(0, 2*pi, spacing)
    for theta in thetas:
        cv2.line(img, (c, r), (int(c+radius*cos(theta)), int(r+radius*sin(theta))), color=255)
    plt.scatter(c, r, c='y', s=100, marker='.')
    plt.imshow(img, cmap='gray')
    plt.show()
    

    【讨论】:

    • 感谢您的输入,但我想我没有说清楚,我使用 Canny edge 找到质心,因为我也希望它找到其他形状的质心,我从圆开始因为这是最简单的形状,但谢谢!
    • @Newyenminh 哦,在这种情况下,这完全有道理!所以我想在那种情况下thetas 的东西不会有什么用处,因为你需要它来处理一般情况,是这样吗?
    • 是的,我认为 theta 在这里用处不大,但感谢您的帮助。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多