我目前正在尝试获取一组图像的轮廓。但是CV2无法返回各种图像的完整轮廓,如下所示。
因此,我正在寻找一种方法来近似轮廓列表的时刻,这是一种让CV2在调用函数时返回单个轮廓的方法" findContours(...)"或者尽可能合并返回到单个轮廓的轮廓列表。 我的代码(已更新)目前包含:
def find_if_close(cnt1,cnt2):
row1,row2 = cnt1.shape[0],cnt2.shape[0]
for i in range(row1):
for j in range(row2):
dist = np.linalg.norm(cnt1[i]-cnt2[j])
if abs(dist) < 50 :
return True
elif i==row1-1 and j==row2-1:
return False
def thresh_callback(thresh, img, gray, blur):
edges = cv2.Canny(blur,thresh,thresh*2)
drawing = np.zeros(img.shape,np.uint8) # Image to draw the contours
image, contours,hierarchy = cv2.findContours(edges,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
LENGTH = len(contours)
status = np.zeros((LENGTH,1))
for i,cnt1 in enumerate(contours):
x = i
if i != LENGTH-1:
for j,cnt2 in enumerate(contours[i+1:]):
x = x+1
dist = find_if_close(cnt1,cnt2)
if dist == True:
val = min(status[i],status[x])
status[x] = status[i] = val
else:
if status[x]==status[i]:
status[x] = i+1
unified = []
maximum = int(status.max())+1
for i in range(maximum):
pos = np.where(status==i)[0]
if pos.size != 0:
cont = np.vstack(contours[i] for i in pos)
unified.append(cont)
cv2.drawContours(img,unified,-1,(0,255,0),2)
cv2.drawContours(drawing,unified,-1,255,-1)
cv2.imshow('output',img)
cv2.imshow('input',drawing)
cv2.waitKey(0)
cv2.destroyAllWindows()
return moments, cx, cy, count
def alter_image(img, blur):
ret, thresh1 = cv2.threshold(blur, 50, 255, cv2.THRESH_BINARY)
bitwise = cv2.bitwise_not(thresh1)
erosion = cv2.erode(bitwise, np.ones((2, 2) ,np.uint8), iterations=1) #15
dilation = cv2.dilate(erosion, np.ones((3, 3) ,np.uint8), iterations=1) #45
return dilation
imgs = cv2.imread('./images/'+str(num)+'.jpg')
img_grey = cv2.cvtColor(imgs,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(img_grey,(5,5),0)
imgs = alter_image(imgs, blur)
thresh = 255
max_thresh = 255
moments, cx, cy, count = thresh_callback(thresh, imgs, img_grey, blur)