Home > Net >  Python OpenCV contour only seems to trace the edges of the image, not the object in the middle
Python OpenCV contour only seems to trace the edges of the image, not the object in the middle

Time:08-11

So i've been using OpenCV on python 3.6 to approximate a shape as a polygon, and plot the polygonal approximation on the binary image. Below, I have my code and the end-result picture.

As you can see here, the green line (the polygonal contour), only traces the edge of the image, so it only counts 4 sides (b/c the picture is a rectangle), completely disregarding the object in the middle.

No clue what's going on. My code worked well with a similar image.

1

img = cv2.imread(img) 
black = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) 
# Apply threshold (just in case gray is not binary image).

# apply morphology close
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3)) ;
morph = cv2.morphologyEx(black, cv2.MORPH_CLOSE, kernel) ;

# get contours and keep largest
contours = cv2.findContours(morph, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) ;
contours = contours[0] if len(contours) == 2 else contours[1]  ;
big_contour = max(contours, key=cv2.contourArea) ;

# draw contour
contour = img.copy() ;
cv2.drawContours(contour, [big_contour], 0, (0,0,255), 1) ; # get number of vertices (sides)
peri = cv2.arcLength(big_contour, True)
approx = cv2.approxPolyDP(big_contour, 0.001 * peri, True)

protrusions = (len(approx) - 3)/3
print('number of sides:',len(approx))
print("number of protrusions: ",protrusions)

cv2.drawContours(contour, [approx], -1, (0, 255, 0), 1)
cv2.drawContours(contour, approx, -1, (255, 0, 0), 2)



# save results
cv2.imwrite("quadrilateral_edges.jpg", edges) ;
cv2.imwrite("quadrilateral_morphology.jpg", morph) ;
cv2.imwrite("quadrilateral_contour.jpg", contour) ;

CodePudding user response:

So i changed one thing instead of using cv2.cvtColor I used a cv2.Canny which gave a good result.

Change the line black = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

to black = cv2.Canny(img, 90, 130)

here is an screenshotof the output

Output

  • Related