CV2:近似时刻/单轮廓返回

时间:2018-03-14 10:17:44

标签: python-3.x opencv image-processing cv2 opencv-contour

我目前正在尝试获取一组图像的轮廓。但是CV2无法返回各种图像的完整轮廓,如下所示。

enter image description here

因此,我正在寻找一种方法来近似轮廓列表的时刻,这是一种让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)

如代码所示,我试图通过侵蚀,扩张,按位变化等变化来改变图像,但结果仍然相同。原始图像可以在下面找到。 enter image description here

图像输出(更新): enter image description here

0 个答案:

没有答案