Dicom 到 PNG 转换 - 输出图像是全黑的

问题描述

使用 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]]

解决方法

根据docs.opencv.org,cv2.imwrite一般“偏好”图像数据为8位表示(即值范围仅从0到255)。

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

我注意到您的图像数据超过 8 位,因此您需要 (a) 缩放它然后将其转换为 class listener(StreamListener): def on_data(self,data): tweet = json.loads(data) # If the returned tweet object is NOT a retweet: if not tweet['retweeted_status']: print('@%s: %s' % (tweet['user']['screen_name'],tweet['text'].encode('ascii','ignore'))) with open('fetched_tweets.csv','a') as tf: tf.writelines('%d,\"%s\",%s,%d,\"%s\"\n' % (tweet['id'],tweet['created_at'],tweet['user']['screen_name'],tweet['user']['followers_count'],tweet['user']['friends_count'],'ignore')#.replace('\n',' ',100).replace(',',100) )) return True ,或 (b) 将位表示减少到 8 位。

(a) 缩放示例:

np.uint8

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

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)

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

,除了这些例外:

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

您可以将图片投射到 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',img) :)

np.uint16
,

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

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