Search code examples
pythonopencvdicomhough-transform

Error when trying to segment circles in DICOM image using openCV and HoughCircles


I am trying to segment circles in a DICOM image. I am trying to implement the hough transform with opencv to do so. I am getting this error:

cv2.error: OpenCV(4.1.0) /Users/travis/build/skvark/opencv-python/opencv/modules/imgproc/src/hough.cpp:1736: error: (-215:Assertion failed) !_image.empty() && _image.type() == CV_8UC1 && (_image.isMat() || _image.isUMat()) in function 'HoughCircles'

Code:

#Segment circle code using openCV
def segment_circles(self): 

    image = np.float(self.image)
    output = image.copy()
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.2, 100)

    if circles is not None:
        circles = np.round(circles[0, :].astype("int"))

        for (x, y, r) in circles:
            cv2.circle(output, (x,y), r, (0, 255, 0), 4)
            cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)

            cv2.imshow("output", np.hstack([image, output]))
            cv2.waitKey(0)
#how self.image is created in another function
self.image = PIL.Image.fromarray(numpy_array)

Thank you in advance for your help.


Solution

  • Please see Wilf's answer for proper fix.

    Quick fix of original code:

    def hough_circles(self):
    
        #load image
        img = self.imager.values[self.imager.index, :, :]
        image8 = np.uint8(img)
        output = image8.copy()
    
        #apply hough transform
        circles = cv2.HoughCircles(image8, cv2.HOUGH_GRADIENT, 1.2, 100)
    
        #place circles and cente rectangle on image
        if circles is not None:
            circles = np.round(circles[0, :].astype("int"))
    
            for (x, y, r) in circles:
                cv2.circle(output, (x,y), r, (0, 255, 0), 4)
                cv2.rectangle(output, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)
    
            cv2.imshow("output", np.hstack([image8, output]))
            cv2.waitKey(0)