此解决方案查看一对图像。该算法评估图像中的形状是否会像钥匙和锁一样网格化。我的回答不会尝试对齐图像。
第一步是找到图像中的轮廓:
left= cv2.imread('/home/stephen/Desktop/left.png')
right = cv2.imread('/home/stephen/Desktop/right.png')
# Resize
left = cv2.resize(left, (320,320))
gray = cv2.cvtColor(left, cv2.COLOR_BGR2GRAY)
_, left_contours, _ = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
# Approximate
left_contour = left_contours[0]
epsilon = 0.005*cv2.arcLength(left_contour,True)
left_contour = cv2.approxPolyDP(left_contour,epsilon,True)
什么是轮廓?轮廓只是位于形状周长上的点列表。三角形的轮廓将有 3 个点,长度为 3。点之间的距离将是三角形中每条腿的长度。
同样,山峰和山谷之间的距离将在您的图像中匹配。为了计算这个距离,我找到了轮廓点之间的距离。由于图像对齐的方式,我只使用了水平距离。
left_dx = []
for point in range(len(left_contour)-1):
a = left_contour[point][0]
b = left_contour[point+1][0]
dist = a[0]-b[0]
left_dx.append(dist)
right_dx = []
for point in range(len(right_contour)-1):
a = right_contour[point][0]
b = right_contour[point+1][0]
# Use the - of the distance becuase this is the key hole, not the key
dist = -distance(a,b)
right_dx.append(dist)
# Reverse so they will fit
right_dx.reverse()
在这一点上,您可以看到轮廓对齐。如果您有更好的图像,轮廓将在此步骤中对齐。我使用 Scipy 进行迭代并检查函数是否对齐。如果这两个函数确实对齐,那么图像中的对象就会网格化。
left_x_values = []
for i in range(len(left_dx)): left_x_values.append(i)
x = np.array(left_x_values)
y = np.array(left_dx)
left_x_new = np.linspace(x.min(), x.max(),500)
f = interp1d(x, y, kind='quadratic')
left_y_smooth=f(left_x_new)
plt.plot (left_x_new, left_y_smooth,c = 'g')
我在自己生成的一对图像上再次尝试了这个:
轮廓:
轮廓点之间的距离:
拟合轮廓: