簡體   English   中英

從質心圍繞圖像畫線

[英]draw lines around the image from the centroid

原圖

設置圖像

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 度或設定的度數繪制將質心連接到形狀中的點的線。

想要的結果

我認為沒有必要使用 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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM