Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot detect small shapes using findContours

Tags:

python

opencv

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

How to solve this problem?

like image 838
Loly Avatar asked Feb 24 '26 14:02

Loly


1 Answers

"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)

enter image description here

like image 50
I.Newton Avatar answered Feb 27 '26 03:02

I.Newton