简体   繁体   English

OpenCV findContours循环Python

[英]OpenCV findContours loop Python

I am having trouble getting my code to find the contours of the images that I create after the first one is created. 创建第一个图像后,我无法获取代码来查找图像轮廓。 The goal of this part of the program is to first create an image such as the following: 该程序这一部分的目标是首先创建一个图像,如下所示:

在此处输入图片说明

And then break it into images such as the following using the color_separator function. 然后使用color_separator函数将其分解为如下图像。 What this does is separate each individual image by color so that from the above image, we would get: 这样做是通过颜色将每个单独的图像分开,以便从上面的图像中我们可以得到:

在此处输入图片说明在此处输入图片说明在此处输入图片说明

Then, I try to find the contours by using basic findContours in OpenCV. 然后,我尝试使用OpenCV中的基本findContours查找轮廓。 The problem lies in the findContours part: it will find the first set of contours; 问题出在findContours部分:它将找到第一组轮廓。 but for the others, the contours are blank. 但是对于其他人,轮廓是空白的。 The images load up correctly; 图像正确加载; everything works up until findContours for all images after the first. 一切正常,直到第一个图像之后的所有图像都找到findContours。 So as an example, the green picture would have it's contours found and not print the "No Contours" check statement; 因此,举例来说,绿色图片将找到轮廓,而不打印“无轮廓”检查语句; but the rest of the images will print the "No Contours" check statement. 但其余图像将打印“无轮廓”检查语句。 If anyone can help, I'd really appreciate it. 如果有人可以提供帮助,我将非常感激。

def getAttributesFromNetwork(self,Network,image):
    ShapeList = []
    AngleList = []
    FillList = []
    SizeList = []
    print Network.letter
    # Open the image path from the Problems (Image Data) folder
    image = Image.open(image)
    grayscale = image.convert("L")
    blackwhite = grayscale.point(self.filter,"1")

    image = blackwhite
    image = image.convert("RGB")
    width,height = image.size
    colorindex = 0
    # Translate the image into pictures with various colors
    while True:
        color = DISTINCT_COLORS[colorindex]
        colorindex += 1
        blackpixel = None
        for x,y,pixel in self.walk(image):
            if pixel == (0,0,0):
                blackpixel = (x,y)
                break
        if not blackpixel:
            break

        neighbors = [blackpixel]
        while len(neighbors) > 0:
            processing = list(neighbors)
            neighbors = []
            for x,y in processing:
                image.putpixel((x,y),color)
                new = [(x-1,y),(x+1,y),(x,y-1),(x,y+1)]
                for x,y, in new:
                    if (x,y) in neighbors:
                        continue
                    if x < 0 or x >= width:
                        continue
                    if y < 0 or y >= height:
                        continue
                    if image.getpixel((x,y)) != (0,0,0):
                        continue
                    neighbors.append((x,y))
    # We use the count to save each network as a different image
    self.count = str(self.count)
    # Save the network image
    image.save("colored"+self.count+".png")
    # Open the network image; here, we'll convert it to a bunch of different 
    # images; each with a different shape
    im = Image.open("colored"+self.count+".png")
    # Separate the images
    colors_dict = color_separator(im)
    #print colors_dict
    # show the images:
    imageCount = 0
    # Iterate through the color dictionary for all of the images
    for key,value in colors_dict.iteritems():
        if key == (255, 255, 255):
            imageCount += 1
            continue
        imageCount = str(imageCount)
        # grab the individual image,
        image = value
        # save it,
        image.save(Network.letter+"coloredSmall"+imageCount+".png")
        # then read it back with OpenCV for processing
        img = cv2.imread(Network.letter+"coloredSmall"+imageCount+".png")
        # Convert it to grayscale; it processes better this way
        imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
        ret,thresh = cv2.threshold(imgray,127,255,0)
        # find the contours in the image
        contours,hierarchy = cv2.findContours(thresh,1,2)
        #count = 0
        # iterate through the contours,
        if not contours:
            print "No Contours"
        for cnt in contours:
            print "Looking through contours"
            #if (count%2) == 1:
                #count = count + 1
                #print "Count2: ",count
                #continue
            # approximate how many sides it has
            approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
            print len(approx)
            if len(approx) == 5:
                print "Half-Arrow"
                ShapeList.append("Half-Arrow")
            if len(approx) == 7:
                print "Arrow"
                ShapeList.append("Arrow")
            elif len(approx) == 3:
                print "Triangle"
                ShapeList.append("Triangle")
            elif len(approx) == 4:
                print "Square"
                ShapeList.append("Square")
            elif len(approx) >= 13:
                print "Circle"
                ShapeList.append("Circle")
            elif len(approx) == 12:
                print "Cross"
                ShapeList.append("Cross")
            (x,y),(MA,ma),angle = cv2.fitEllipse(cnt)
            AngleList.append(angle)
            #count = count + 1
            #print "Count: ",count3
            print ShapeList
        cv2.imshow("img",img)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
        imageCount = int(imageCount)
        imageCount += 1

The problem was that the colors on the images were too dark when converted to grayscale. 问题是转换为灰度时图像上的颜色太暗。 The green one was fine; 绿色的很好。 but the dark blue did not convert well to grayscale at all. 但是深蓝色根本无法很好地转换为灰度。 Moral of the story: When converting to grayscale from RGB, make sure your colors are light enough to convert. 故事的寓意:从RGB转换为灰度时,请确保您的颜色足够浅以进行转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM