Reputation: 1942
I am using Python 2.7 and OpenCV 3.0. I am doing a project to detecting the car license plate.
I am now checking the number of vertex of the contours. If there are 4 vertex(number of elements in approx), then it is more likely to be a rectangle/ parallelogram/ quadrilateral .
(cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
cnts=sorted(cnts, key = cv2.contourArea, reverse = True)[:10]
# loop over our contours
for c in cnts:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
if len(approx) == 4 and ratio(approx):
cv2.drawContours(image, [approx], -1, (0,255,0), 3)
And I got two quadrilaterals with array.
However, you can see, there is an irregular polygon. This is the array:
[[[209 198]]
[[466 94]]
[[259 153]]
[[247 1]]]
I am asking for how can I omitted the irregular quadrilateral. Thank you
Upvotes: 3
Views: 9831
Reputation: 629
Note: If you know how many sides your polynomial is supposed to have, for example if you are looking for convex quadrilaterals in an image, then you only need call:
hull = cv2.convexHull(approx, returnPoints = False)
And then you only need to check that the len(hull) == num_expected_sides
, in the quadrilateral case:
len(cv2.convexHull(approx, returnPoints = False)) == 4
Upvotes: 1
Reputation: 18593
As suggested by https://stackoverflow.com/users/4606294/user89161 in his comment Opencv detect quadrilateral in Python
maybe you can add a test on your approx
, something like:
hull = cv2.convexHull(approx,returnPoints = False)
defects = cv2.convexityDefects(approx,hull)
sum_of_defects=0
for i in range(defects.shape[0]):
s,e,f,d = defects[i,0]
sum_of_defects=sum_of_defects+d
if sum_of_defects <= threshold:
print "approx is convex"
else:
print "approx is not convex"
and you have to properly choose threshold
, I will start with threshold=3
or something like that. Theoretically threshold
should be zero.
Upvotes: 2