Home > Software design >  OpenCV: Hough Circles, trouble detecting object
OpenCV: Hough Circles, trouble detecting object

Time:04-09

I am a complete beginner when it comes to OpenCV, I have no clue where to start when trying to detect circles of a certain size, below is my current code (not much) along with the image I am trying to detect, if anyone could help me or give me some advice it would be much appreciated, (i have converted image to grayscale and added gaussian blur so it is easier to detect) Thanks!

Image

import cv2
import numpy as np


test = cv2.imread('test.jpg')
gray_img = cv2.cvtColor(test, cv2.COLOR_BGR2GRAY)
img = cv2.medianBlur(gray_img,  5)
cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)


cv2.imshow("HoughCirlces",  test)
cv2.waitKey()
cv2.destroyAllWindows()

CodePudding user response:

great work, you're almost there, all you have to do now is actually apply the CHT. The function you are looking for is cv2.HoughCircles(). You need to pass the image, in your case you can use either img or cimg and some parameters that might require tuning. Here is some template code

import cv2
import numpy as np


test = cv2.imread('test.jpg')
gray_img = cv2.cvtColor(test, cv2.COLOR_BGR2GRAY)
img = cv2.medianBlur(gray_img,  5)
cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)

circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,20,
                            param1=50,param2=30,minRadius=0,maxRadius=0)

circles = np.uint16(np.around(circles))
for i in circles[0,:]:
    # draw the outer circle
    cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
    # draw the center of the circle
    cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)

cv2.imshow("HoughCirlces",  test)
cv2.waitKey()
cv2.destroyAllWindows()

You can also take a look at the documentation and tutorial. I'll link them below. Tutorial: https://docs.opencv.org/4.x/da/d53/tutorial_py_houghcircles.html Docs: https://docs.opencv.org/4.x/dd/d1a/group__imgproc__feature.html#ga47849c3be0d0406ad3ca45db65a25d2d

  • Related