1

更新:我自己计算的距离与返回的距离之间的比率似乎cv2正好是 256。这并不奇怪,因为查看他们的代码(此处为第 394 行)显示像素距离乘以 256。我只是不不明白为什么,我猜。


cv2.convexityDefects用来寻找某种形状的凸缺陷。我希望计算缺陷的深度(到凸包的距离,正如这里很好解释的那样)。

但是,我得到的距离太大而无法理解。我还尝试使用 cv2.convexityDefects 的起点和终点输出参数(参见下面的代码)手动计算距离,并获得更合理的结果。

计算的距离cv2.convexityDefects是,

>> d
array([21315, 26578, 19093, 56472, 35230, 20476, 26825], dtype=int32)

在大约 500 像素宽的图像的上下文中,这完全没有意义。我究竟做错了什么?


更多信息:

这是我为此测试创建的图像(嗯,我的意思是艺术品),

凸缺陷的测试图像

这是代码:

from numpy.linalg import norm

# Load an image
img = cv2.imread('buff.png')

# Threshold
ret, img = cv2.threshold(img,127,255,cv2.THRESH_BINARY)

# Detect edges
edges = cv2.Canny(img, 1, 2)

# Find contours
cnts, h = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

# Find convex hull
hull = cv2.convexHull(cnts[0], returnPoints = False)

# Find defects
defects = cv2.convexityDefects(cnts[0], np.sort(np.squeeze(hull)))
# Reshape the output
s = np.reshape(defects,(-1,4))[:,0] # start point idx
e = np.reshape(defects,(-1,4))[:,1] # end point idx
f = np.reshape(defects,(-1,4))[:,2] # defect idx
d = np.reshape(defects,(-1,4))[:,3] # distances as calculated by cv2.convexityDefects

# Draw contours in red, convex hull in blue
img = cv2.drawContours(img, cnts[0], -1, (255,0,0), 2)
img = cv2.polylines(img, [cnts[0][np.squeeze(hull)]], True, (0,0,255), 3)

# Calculate distances manually and put in a list d2
d2 = list()
for i in range(len(f)):
    # Draw the defects in blue, start points in pink:
    img = cv2.circle(img, tuple(cnts[0][f[i]][0]), 5,(0, 0, 255), -1)
    img = cv2.circle(img, tuple(cnts[0][s[i]][0]), 5,(255, 0, 255), -1)

    # Manually calculate the distances as the distances between the defects (blue points)
    # and the line defined between each pair of start and end points (pink here, for demonstration)
    d2.append(norm(np.cross(cnts[0][s[i]][0]-cnts[0][e[i]][0], cnts[0][e[i]][0]-cnts[0][f[i]][0]))/norm(cnts[0][s[i]][0]-cnts[0][e[i]][0]))
    
pp.imshow(img)
pp.show()

这是上面代码的输出,当应用于测试图像时:

代码计算的凸点

4

1 回答 1

0

看起来我自己计算的距离与返回的距离之间的比率cv2正好是 256。这并不奇怪,因为查看他们的代码(此处的第 394 行)显示以像素为单位的距离乘以 256。我只是不明白为什么,我猜。

于 2021-08-31T03:57:22.377 回答