简体   繁体   中英

Python - OpenCV - Circle detection with HoughCircles

img = cv2.imread('/home/user/Documents/pycharm-workspace/ImageProcessing/SDC10004.JPG', 1)
img = cv2.medianBlur(img, 5)
cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)

circles = cv2.HoughCircles(img, cv2.cv.CV_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.imwrite('circles_detected.JPG', cimg)

I am trying to detect circles in my image with the HoughCircles function from opencv.

This is the error message i get:

cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) 
cv2.error: /build/buildd/opencv-2.4.8+dfsg1/modules/imgproc/src/color.cpp:3789: error: (-215) scn == 1 && (dcn == 3 || dcn == 4) in function cvtColor

I also tried to load the grayscale image like this and leave the cvtColor function off

img = cv2.imread('/home/user/Documents/pycharm-workspace/ImageProcessing/SDC10004.JPG', 0)

However the program just takes forever to run. I have waited more than 10 minutes and nothing has happened.

Can someone help me please?

For your first error, you are opening your image in color mode with

img = cv2.imread('/home/user/Documents/pycharm-workspace/ImageProcessing/SDC10004.JPG', 1) #1 means color

and then trying to convert it treating it as a grayscale image with

cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) #GRAY2BGR means gray to BGR.
#You don't have a grayscale image to begin with.

For your second problem, Hough transform is a long process. I tried your code with a 200 * 200 image and it was instantaneous. Try smaller images first to see if it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM