2017-03-01 132 views
2

我正在使用python openCV库来获取简单图像中的轮廓坐标。据我所知,轮廓中点的顺序将是findContour()方法返回的顺序。OpenCV的findContours方法中的重复项

但findContour()返回的一组点重复其中。如果订单保留,那么如何有重复?

如何读取输出?

下面是代码

import numpy as np 
import cv2 
from pylab import plot,show 

from PIL import Image 


def get_contours(im): 

    imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) 
    ret,thresh = cv2.threshold(imgray,127,255,0) 
    im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 

    return im2, contours, hierarchy 

def main(): 
    im = cv2.imread('border.jpeg') 

    contour_image, contours, hierarchy = get_contours(im) 

    contour_points = [] 
    for pt in contours[1]: 
     contour_points.append((pt[0][0],pt[0][1])) 
     plot(pt[0][0],pt[0][1]) 

    if len(contour_points)!= len(set(contour_points)): 
     print "has_duplicates" 
    else: 
     print "no duplicates" 

main() 

Here is the image

回答

1

目的你发现轮廓的包含一些1个像素宽“瓶颈”,从而在相对的两侧边共享一个顶点。

最好用图片来说明这一点。

想象一下这种情况在一个4x5像素的图片:

让我们运行一个简短的脚本找到这个轮廓:

import cv2 
import numpy as np 

a = np.array([[0,0,0,0],[0,0,1,0],[0,1,0,0],[0,0,1,0],[0,0,0,0]],dtype=np.uint8) 
>>> _, contours, _ = cv2.findContours(a,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) 
>>> print contours 
[array([[[2, 1]], 
     [[1, 2]], 
     [[2, 3]], 
     [[1, 2]]])] 

如果我们得出这样的,它变得相当显而易见:

+0

Bu t根据你的箭头标记,数组不应该以[2,1]结束。为什么该点只出现一次? – MaPY

+0

@MadhuriPalagummi最后一条边(在最后和第一个顶点之间)是隐式的(轮廓总是闭合的),所以顶点不会被重复。 (AFAIK没有很好的记录,但是从源代码和经验中得到证实) –

+0

因此,除了第一点以外,每个点都应该列出两次? 是吗? – MaPY