第一步,您应该使用适当的工具将图像转换为二进制图像,例如 cv2.cvtColor()、cv2.threshold()、cv2.bitwise_not()、...(取决于图像) - 这意味着您的图像将仅包含黑色或白色像素。
例子:
然后你应该在图像上找到你的轮廓 (cv2.findContours) 并用大小标准 (cv2.contourArea()) 过滤掉它们以消除图像中间的大五边形等其他轮廓。
下一步,您应该找到每个轮廓的矩 (cv2.moments()),这样您就可以获得轮廓中心的 x 和 y 坐标并将它们放入列表中。(注意将正确的 x 和 y 坐标附加在一起)。
获得点后,您可以计算所有点之间的距离(使用两点之间的距离公式 - sqrt((x2-x1)^2+(y2-y1)^2) )
然后,您可以使用任何您想要获取每个点的最短距离点坐标的逻辑(在下面的示例中,我将它们压缩到一个列表中,并创建了一个包含每个点的距离、x 和 y 坐标的数组)。
代码示例:
import numpy as np
import cv2
img = cv2.imread('points.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, threshold = cv2.threshold(gray,150,255,cv2.THRESH_BINARY)
cv2.bitwise_not(threshold, threshold)
im, contours, hierarchy = cv2.findContours(threshold,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
listx = []
listy=[]
for i in range(0, len(contours)):
c = contours[i]
size = cv2.contourArea(c)
if size < 1000:
M = cv2.moments(c)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
listx.append(cX)
listy.append(cY)
listxy = list(zip(listx,listy))
listxy = np.array(listxy)
for i in range(0, len(listxy)):
x1 = listxy[i,0]
y1 = listxy[i,1]
distance = 0
secondx = []
secondy = []
dist_listappend = []
sort = []
for j in range(0, len(listxy)):
if i == j:
pass
else:
x2 = listxy[j,0]
y2 = listxy[j,1]
distance = np.sqrt((x1-x2)**2 + (y1-y2)**2)
secondx.append(x2)
secondy.append(y2)
dist_listappend.append(distance)
secondxy = list(zip(dist_listappend,secondx,secondy))
sort = sorted(secondxy, key=lambda second: second[0])
sort = np.array(sort)
cv2.line(img, (x1,y1), (int(sort[0,1]), int(sort[0,2])), (0,0,255), 2)
cv2.imshow('img', img)
cv2.imwrite('connected.png', img)
Run Code Online (Sandbox Code Playgroud)
结果:
正如您在结果中看到的,现在每个点都与其最近的相邻点相连。希望它会有所帮助,或者至少提供有关如何解决问题的想法。干杯!