cmplx96
cmplx96

Reputation: 1661

python opencv - HoughCircles error after pixel manipulation

def detect_circles():
    img = cv2.imread('img.JPG', 0)
    #img = cv2.medianBlur(img, 3)
    #cim= cv2.GaussianBlur(img, (15, 15), 0)
    cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)

    circles = cv2.HoughCircles(img, cv2.cv.CV_HOUGH_GRADIENT, 1, 30,param1=100,param2=39,minRadius=25,maxRadius=70)
    circles = np.uint16(np.around(circles))
    count = 0
    for i in circles[0, :]:
        count = count + 1
        # 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)
    print(count)

This function is designed to detect circles in an image. It works alright but i need to differentiate between colors. So i wrote this function which sets the G and R value of every pixel to 0.

def iterate_image():
    img = read_img('SDC10004.JPG')
    height = img.shape[0]
    width = img.shape[1]
    for i in range(height):
        for j in range(width):
            #img.itemset((i,j, 0), 100)
            img.itemset((i,j, 1), 0)
            img.itemset((i,j, 2), 0)

    write_img(img,'SDC10004_selfmade_blue.JPG')

When i try to detect circles with the blue pixel image i get this error message:

Traceback (most recent call last):
File "/home/user/Documents/workspace/ImageProcessing/Main.py", line 107, in <module>
detect_circles();
File "/home/user/Documents/workspace/ImageProcessing/Main.py", line 94, in detect_circles
circles = np.uint16(np.around(circles))
File "/usr/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 2610, in around
return _wrapit(a, 'round', decimals, out)
File "/usr/lib/python2.7/dist-packages/numpy/core/fromnumeric.py", line 43, in _wrapit
result = getattr(asarray(obj), method)(*args, **kwds)
AttributeError: rint

Has anyone encoutered this before?

Upvotes: 0

Views: 951

Answers (1)

NAmorim
NAmorim

Reputation: 706

So, I believe I found out what is the problem here.

HoughCircles ins't tricky, you just have to be careful with it's parameterization. This method is based on Canny edge detector which in turn thresholds grayscale images.

The formula which opencv uses to grayscale images is given by:

RGB_to_Gray: 0.299.R + 0.587.G + 0.114.B

Since you are zeroing two of the three RGB channels, the intensity of grayscale values will decrease. As a result, your threshold avoids any circle detection and cv2.HoughCircles returns None. Consequently, since you are not testing if circles is of type None, your script won't progress when you try to perform np.around(None).

Adjusting param1 on cv2.HoughCircles should do the trick.

param1 – First method-specific parameter. In case of CV_HOUGH_GRADIENT , it is the higher threshold of the two passed to the Canny() edge detector (the lower one is twice smaller)

HoughCircles param1 source.

Upvotes: 1

Related Questions