正如 comments 中所提到的,您需要使用凸度缺陷.关于这一点的OpenCV教程可以找到here.
我在您的示例图像上try 了以下代码,它可以在您的测试图像上运行.
import cv2
import matplotlib.pyplot as plt
# Read the image, ignore conversions that I did here.
img= cv2.imread('img.png')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
_, img_gray = cv2.threshold(img_gray,150,255,cv2.THRESH_BINARY)
# Find contours
contours, hierarchy = cv2.findContours(img_gray, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
# Find the convex hulls and defects, assuming there might exist more than one contour.
hull_list= []
defect_list= []
for i in range(len(contours)):
hull = cv2.convexHull(contours[i], returnPoints= False)
defects = cv2.convexityDefects(contours[i],hull)
hull = cv2.convexHull(contours[i])
hull_list.append(hull)
defect_list.append(defects)
# Draw.
for idx, defects in enumerate(defect_list):
cv2.drawContours(img, hull_list, idx, (255,0,0),2) # remove if you do not want the contour.
for i in range(defects.shape[0]):
s,e,_,d = defects[i,0]
if d>512: # This filters places that are very close to be convex. Change it to zero and see what happens !!!!
start = tuple(contours[idx][s][0])
end = tuple(contours[idx][e][0])
cv2.line(img,start,end,[0,255,0],2)
plt.imshow(img)
plt.show()