openCV: cannot detect small shapes using findConto

2020-07-21 01:25发布

问题:

I'm trying to detect specific types of shapes - triangle, square, circle - in a binary image using cv2.findContours, and to color each type with differnt color. The following code works for big shapes, but it's not working for small shapes - about 10*10 px.

import numpy as np
import cv2

img = cv2.imread('1.jpg') gray = cv2.imread('1.jpg',0)

ret,thresh = cv2.threshold(gray,127,255,1)

contours,h = cv2.findContours(thresh,cv2.RETR_CCOMP,cv2.CHAIN_APPROX_NONE)

for cnt in contours: approx = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True) print len(approx) if len(approx)==3: print "triangle" cv2.drawContours(img,[cnt],0,(122,212,78),-1) elif len(approx)==4: print "square" cv2.drawContours(img,[cnt],0,(94,234,255),-1) elif len(approx) > 15: print "circle" cv2.drawContours(img,[cnt],0,(220,152,91),-1)

cv2.imshow('img',img) cv2.waitKey(0)

cv2.destroyAllWindows()

the image I used:before

and the result:after

I'd be very thankful if you could try to help me solve this problem!

回答1:

"The second argument in cv2.approxPolyDP is called epsilon, which is maximum distance from contour to approximated contour. It is an accuracy parameter. A wise selection of epsilon is needed to get the correct output."

The Output of the same code with the following change-

approx = cv2.approxPolyDP(cnt,.03*cv2.arcLength(cnt,True),True)



标签: python opencv