Detecting circle using hough transformation

Viewed 429

I was trying to detect the coins in an given image to draw vertical line or grouping the coins which falls under the same straight line.

import cv2
from PIL import Image
import numpy as np

import matplotlib.pyplot as plt
img = Image.open("coin.jpg")
imgUMat = np.float32(img)
gray = cv2.cvtColor(imgUMat, cv2.COLOR_BGR2GRAY)
#plt.imshow(img)
#gray = (np.float32(imgUMat), cv2.COLOR_RGB2GRAY)
#gray = cv2.cvtColor(cv2.UMat(img), cv2.COLOR_RGB2GRAY)
#gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
#gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gray = cv2.resize(gray,None,fx=0.25, fy=0.25, interpolation = cv2.INTER_CUBIC)

img = cv2.medianBlur(gray,1)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20,
              param1=30,
              param2=15,
              minRadius=0,
              maxRadius=0)
#circles = cv2.HoughCircles(gray,cv2.HOUGH_GRADIENT,1,100,param1=100,param2=1)
if (circles!=None):
    i = np.uint16(np.around(circles))
    cv2.circle(gray,(i[0,0,0],i[0,0,1]),i[0,0,2],(255,255,255),1)
    cv2.circle(gray,(i[0,0,0],i[0,0,1]),1,(255,255,255),1)
    center_x.append(i[0,0,0])
    center_y.append(i[0,0,1])

When I ran the code, I got an error at circles variable saying that,

error: OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\imgproc\src\hough.cpp:1728: error: (-215:Assertion failed) !_image.empty() && _image.type() == CV_8UC1 && (_image.isMat() || _image.isUMat()) in function 'cv::HoughCircles'

1 Answers

You could try to read your image with opencv instead of pil.

It would look like this:

import cv2
import numpy as np

gray = cv2.imread('coin.png', 0) # The zero reads the image in gray scale
gray = cv2.resize(gray,None,fx=0.25, fy=0.25, interpolation = cv2.INTER_CUBIC)

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

print (circles)

I am not sure what you want to do in your if statement. But I think you should also change this since center_x and center_y are not defined. HoughCircles will also return a Numpy array, therefore you can not use != None I think this works better.

center_x, center_y = [], []
if (len(circles) > 0):
    i = np.uint16(np.around(circles))
    cv2.circle(gray,(i[0,0,0],i[0,0,1]),i[0,0,2],(255,255,255),1)
    cv2.circle(gray,(i[0,0,0],i[0,0,1]),1,(255,255,255),1)
    center_x.append(i[0,0,0])
    center_y.append(i[0,0,1])
Related