【问题标题】:Dicom to PNG Conversion - output image is completely blackDicom 到 PNG 的转换 - 输出图像完全是黑色的
【发布时间】:2021-07-28 08:13:44
【问题描述】:

使用 Python 将 dicom 转换为 png 时,没有出现任何错误。 输出文件是完整的黑色,虽然图像数组有变量值。

代码:

import pydicom
import cv2
import os

dicom = pydicom.dcmread(inputdir + f)
# print("dicom", dicom)
img = dicom.pixel_array
print("img", img)
cv2.imwrite(outdir + f.replace('.dcm','.png'),img)

图像数组(供参考):

[[585 585 570 ... 570 572 570]
[585 585 585 ... 572 575 572]
[585 585 585 ... 553 568 575]
...
[854 854 854 ... 778 783 787]
[854 854 856 ... 783 785 787]
[854 856 856 ... 785 790 759]]

【问题讨论】:

    标签: python cv2 pydicom


    【解决方案1】:

    根据docs.opencv.org,cv2.imwrite 通常“更喜欢”图像数据以 8 位表示(即值范围仅从 0 到 255)。

    一般情况下,只有 8 位单通道或 3 通道(带“BGR”通道 order) 可以使用此功能保存图像...

    我注意到您的图像数据超过 8 位,因此您需要 (a) 对其进行缩放然后将其转换为 np.uint8,或者 (b) 将位表示减少到 8 位。

    (a) 缩放示例:

    import numpy as np  # assuming that you have numpy installed
    img = np.array(img, dtype = float) 
    img = (img - img.min()) / (img.max() - img.min()) * 255.0  
    img = img.astype(np.uint8)
    cv2.imwrite(outdir + f.replace('.dcm','.png'),img)
    

    或者,(b) 移位到 8 位的示例:

    bit_depth = 10  #  assuming you know the bit representation
    img = np.array(img, dtype = np.uint16)
    img = img >> (bit_depth - 8)  
    img = img.astype(np.uint8)
    cv2.imwrite(outdir + f.replace('.dcm','.png'),img)
    

    但是由于您将图像保存为 PNG 格式,所以这里的方法更短...

    ,但有以下例外:

    • 16 位无符号 (CV_16U) 图像可以保存为 PNG、JPEG 2000 和 TIFF 格式
    • ...

    您可以将您的图像投射到np.uint16 :)

    img = img.astype(np.uint16)
    cv2.imwrite(outdir + f.replace('.dcm','.png'),img)
    

    【讨论】:

    • 我相信这是正确的。我有一些使用 pydicom 和 IRCC 的代码,在研究/谷歌搜索如何保存它们的 16 位 PNG 版本后,跳过了 CV 和 Pillow,因为它们都对 16 位单通道 PNG 有限制。相反,我找到了一个专用的(不记得名字,但可能很容易找到)PNG 处理模块,它可以正确处理事情。用过,没问题。
    【解决方案2】:

    在“dicom.pixel_array”之后添加下一行代码就可以了。

    ## Rescaling grey scale between 0-255
    scaled_img = (np.maximum(img,0) / img.max()) * 255.0
    

    【讨论】:

      猜你喜欢
      • 2017-01-08
      • 1970-01-01
      • 2016-02-15
      • 2020-08-01
      • 1970-01-01
      • 2016-03-31
      • 2023-04-05
      • 1970-01-01
      • 2016-05-23
      相关资源
      最近更新 更多