在使用OpenCV和HoughCircles对DICOM图像分割圆时遇到错误

2024-09-27 09:30:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在DICOM图像中分割圆。我正在尝试用opencv实现hough变换。我得到这个错误:

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'

代码:

#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)

事先谢谢你的帮助。你知道吗


Tags: inimageselfoutputisnpfunctionerror
3条回答

这是一个可以用来从磁盘读取DICOM文件并执行Hough变换的工作流

    import pydicom
    import cv2
    import numpy as np

    # read the DICOM file
    d16=pydicom.read_file('view0010.dcm')

    print(f"original data type={d16.pixel_array.dtype}")

    # rescale original 16 bit image to 8 bit values [0,255]
    x0=d16.pixel_array.min()
    x1=d16.pixel_array.max()
    y0=0
    y1=255.0
    i8=((d16.pixel_array-x0)*((y1-y0)/(x1-x0)))+y0

    # create new array with rescaled values and unsigned 8 bit data type
    o8=i8.astype(np.uint8)

    print(f"rescaled data type={o8.dtype}")

    # do the Hough transform
    h=cv2.HoughCircles(o8, cv2.HOUGH_GRADIENT, 1.2, 100)

    print(f"h={h}")

当我在我的电脑上用一个真实的MR图像运行这个时,这里是输出。。。你知道吗

    original data type=int16
    rescaled data type=uint8
    h=[[[172.20001 259.80002 154.92001]
      [319.80002 273.      161.64   ]]]

当然,Hough变换的结果对你来说是不同的,但是我认为它显示了在真实的DICOM图像上运行cv2 houghcirles函数所必须做的事情。你知道吗

请参阅威尔夫的答案,以获得正确的解决方案。你知道吗

原始代码的快速修复:

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)

我想我应该在“gray=”后面加几行代码。。。“行分别测试这些条件。你确定gray().isEmpty()真的是假的吗?只需一两分钟就可以找出哪些条件无法通过验证测试。你知道吗

图像是什么形态?你知道吗

相关问题 更多 >

    热门问题