Ask Your Question

in Python OpenCV use of hierarchy for findContours

asked 2014-04-05 04:03:21 -0500

Francesco Sgaramella gravatar image

updated 2017-11-12 06:23:15 -0500

I implemented a Python script for recognizing shapes in hand drawings. However, the script recognizes more shapes than needed.

Here is an example picture:

image description

and this is the output of the script:

image description

Part of the code I wrote is the following:

def create_graph(vertex, color):
    for g in range(0, len(vertex)-1):
        for y in range(0, len(vertex[0][0])-1):
  , (vertex[g][0][y], vertex[g][0][y+1]), 3, (255,255,255), -1)
            cv2.line(newimg, (vertex[g][0][y], vertex[g][0][y+1]), (vertex[g+1][0][y], vertex[g+1][0][y+1]), color, 2)
    cv2.line(newimg, (vertex[len(vertex)-1][0][0], vertex[len(vertex)-1][0][1]), (vertex[0][0][0], vertex[0][0][1]), color, 2)

img = cv2.imread('star.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

#Remove of noise, if any
kernel = np.ones((2, 2),np.uint8)
erosion = cv2.erode(gray, kernel, iterations = 1)

#Create a new image of the same size of the starting image
height, width = gray.shape
newimg = np.zeros((height, width, 3), np.uint8)

#Canny edge detector
thresh = 175
edges = cv2.Canny(erosion, thresh, thresh*2)

contours,hierarchy = cv2.findContours(edges,, cv2.CHAIN_APPROX_SIMPLE)
for b,cnt in enumerate(contours):
    if hierarchy[0,b,3] == -1: #<-the mistake might be here
       approx = cv2.approxPolyDP(cnt,0.015*cv2.arcLength(cnt,True), True)
       clr = (255, 0, 0)
       create_graph(approx, clr) #function for drawing the found contours in the new img
cv2.imwrite('starg.jpg', newimg)

I did not post all the code because is useless. I think that I am mistaking the use of hierarchy for finding the contours. I am not such a Python expert and I did not understand that well the use of hierarchy in the contours. Does anybody have suggestions?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2014-04-05 04:43:39 -0500

Haris gravatar image

updated 2014-04-05 04:44:51 -0500

So you need only outer contour, then instead of CV_RETR_CCOMP use CV_RETR_EXTERNAL which retrieves only the extreme outer contours. Also see the answer here might be helpful.

edit flag offensive delete link more

Question Tools


Asked: 2014-04-05 04:03:21 -0500

Seen: 1,558 times

Last updated: Apr 05 '14