多个dicom图像变为灰色

2024-10-01 04:49:39 发布

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

我正在使用基于区域的图像分割为此我需要将我的dicom文件转换为灰度,我在一个图像中执行它工作良好,但在多个图像中给我一个错误。你知道吗

def DicomtoRGB(dicomfile,bt,wt):
    """Create new image(numpy array) filled with certain color in RGB"""
    # Create black blank image
    image = np.zeros((dicomfile.shape[0], dicomfile.shape[1], 3), np.uint8)
    #loops on image height and width
    i=0
    j=0
    while i<dicomfile.shape[0]:
        j=0
        while j<dicomfile.shape[1]:
            color = yaxpb(dicom_file.pixel_array[i][j],bt,wt) #linear transformation to be adapted
            image[i][j] = (color,color,color)## same R,G, B value to obtain greyscale
            j=j+1
        i=i+1
    return image

def yaxpb(pxvalue,bt,wt):
    if pxvalue < bt:
        y=0
    elif pxvalue > wt:
        y=255
    else:
        y=pxvalue*255/(wt-bt)-255*bt/(wt-bt)
    return y

for filename in os.listdir(path):
    dicom_file = os.path.join(path,filename)   
    exists = os.path.isfile(dicom_file) 
    print(filename)
    ds = dicom.read_file(dicom_file)
    dcm_sample=ds.pixel_array*128
    print(type(dcm_sample))

    image=DicomtoRGB(dcm_sample,bt=0,wt=1400)
    print(type(image))
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    gray = rgb2gray(image)
    plt.imshow(gray, cmap='gray') 

这是我的错误

AttributeError                            Traceback (most recent call last)
<ipython-input-22-575cc8822b54> in <module>
      7     print(type(dcm_sample))
      8 
----> 9     image=DicomtoRGB(dcm_sample,bt=0,wt=1400)
     10     print(type(image))
     11     gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

<ipython-input-20-9c7a51460e87> in DicomtoRGB(dicomfile, bt, wt)
     14         while j<dicomfile.shape[1]:
     15             print(type(dicom_file))
---> 16             color = yaxpb(dicom_file.pxvalue[i][j],bt,wt) #linear transformation to be adapted
     17             image[i][j] = (color,color,color)## same R,G, B value to obtain greyscale
     18             j=j+1

AttributeError: 'str' object has no attribute 'pixel_array'

或者有人请参考我的任何链接,其中多个dicom图像转换成灰度。你知道吗


Tags: sample图像imagetypefiledicomcolorbt
2条回答

你的问题的最后一行意味着你很乐意考虑其他的可能性,所以我建议ImageMagick,它安装在大多数Linux发行版上,适用于macOS和Windows。你知道吗

因此,就在终端中,您可以将所有Dicom图像转换为灰度,并自动将亮度级别设置为全范围,另存为PNG格式,使用:

magick mogrify -format PNG -colorspace gray -auto-level *.dcm

或者,如果要将它们保存为JPEG格式,请使用:

mkdir grayscale
magic mogrify -format JPEG -path grayscale -colorspace gray -auto-level *.dcm

如果您使用的是旧版本的v6ImageMagick,请从上面显示的命令中省略magick。你知道吗

这条线就是问题所在:

color = yaxpb(dicom_file.pixel_array[i][j],bt,wt)

dicom_file是从for循环到文件的路径,而不是numpy数组。我想你想要的是dicomfile而不是dicom_file.pixel_array

color = yaxpb(dicomfile[i][j],bt,wt)

相关问题 更多 >