Home > database >  why can't I use HoughCircles inside a python function?
why can't I use HoughCircles inside a python function?

Time:10-15

Not sure what I'm doing wrong, but I can't get HoughCircles to run inside of a function...

import cv2
import numpy as np

def test(image):
    circles = cv2.HoughCircles(image, cv2.HOUGH_GRADIENT, 4, 70, minRadius=70, maxRadius=74)
    if circles is not None:
        circles = np.uint16(np.around(circles))
    for x, y, r in circles:
        cv2.circle(image, (x, y), r, [0, 0, 255], 2)
    return image
img = cv2.imread('initial_frame.png')
image2 = test(img)

cv2.imshow('test', image2)
cv2.waitKey(0)
cv2.destroyAllWindows()

This results in ...

circles = cv2.HoughCircles(image, cv2.HOUGH_GRADIENT, 4, 70, minRadius=70, maxRadius=74)
cv2.error: OpenCV(4.5.3) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-1i5nllza\opencv\modules\imgproc\src\hough.cpp:2253: error: (-215:Assertion failed) !_image.empty() && _image.type() == CV_8UC1 && (_image.isMat() || _image.isUMat()) in function 'cv::HoughCircles'

If I remove the call to HoughCircles, then image2 is shown as requested.

CodePudding user response:

About interpreting the error. It comes from hough.cpp#L1659:

CV_Assert(!_image.empty() && _image.type() == CV_8UC1 && (_image.isMat() || _image.isUMat()));

Breaking it down, all the following conditions have to be true:

  • !_image.empty(): the input image should not be empty;
  • _image.type() == CV_8UC1: the input image must be 8U (8-bit unsigned, np.uint8) and C1 (single-channel);
  • _image.isMat() || _image.isUMat(): check if the input is Mat or UMat (in Python, it has to be a numpy array);

The issue that is affecting you is you can only call cv2.HoughCircles() on a single-channel (greyscale) image, your image has 3 channels. Convert your image to greyscale and then try again.

  • Related