Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python OpenCV - Trouble detecting tiny "holes" (circles)

I'm trying to detect "holes" in a drawing, that is to say, they aren't quite circles, they're of varying size. The images are always black and white. Just trying to get my head around this problem, I took an example from the Python documentation:

import cv2
from cv2 import *
import numpy as np

img = cv2.imread('hole_test.jpg',0)
img = cv2.medianBlur(img,5)
cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)

circles = cv2.HoughCircles(img,cv2.cv.CV_HOUGH_GRADIENT,1,5,param1=200,param2=100,minRadius=0,maxRadius=0)

circles = np.uint16(np.around(circles))
for i in circles[0,:]:
    # pinpoint hole
    cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)     
cv2.imshow('holes detected',cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()

The holes detected are few and far between. Is there anything I can do to improve the accuracy of this example, or is this not the best way to achieve this?

This is an example image, simply to show the various size/shape of "holes" I'm aiming to find.

example image

Example 2 as requested

Example 2 as requested:

like image 750
Dr.Avalanche Avatar asked Nov 01 '13 13:11

Dr.Avalanche


1 Answers

enter image description here

code

import cv2
import numpy as np

im = cv2.imread('holes2.jpg')

gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
gray=cv2.threshold(gray,20,255,cv2.THRESH_BINARY)[1]
cv2.imshow('gray',gray)

contours,hierarchy = cv2.findContours(gray,cv2.RETR_LIST ,cv2.CHAIN_APPROX_SIMPLE   )

for cnt in contours:
    area = cv2.contourArea(cnt)
    if area<400:
        cv2.drawContours(im,[cnt],0,(255,0,0),2)

cv2.imshow('im',im)
cv2.waitKey()
like image 53
Zaw Lin Avatar answered Sep 27 '22 16:09

Zaw Lin