import pydicom
import numpy as np
#np.set_printoptions(threshold=np.inf)
import os
import cv2
PathDicom="E:\2_DicomPython\chestDataset\90844786-CT-16705831-2022-03-01-Thorax^07_ZRY_Ribs (Adult)"
dcm = pydicom.read_file("E:\2_DicomPython\chestDataset\90844786-CT-16705831-2022-03-01-Thorax^07_ZRY_Ribs (Adult)\90844786-Thorax^07_ZRY_Ribs (Adult)-2022-03-01_0004_0001_760957850.dcm")
slope = dcm.RescaleSlope
intercept = dcm.RescaleIntercept # 可以从dcm文件中读出
listFilesDCM = [] # 用lstFilesDCM作为存放DICOM files的列表
FilesDCM = []
#将所有dicom文件读入
for PathName, subdirList, fileList in os.walk(PathDicom):
for filename in fileList:
if ".dcm" in filename.lower(): # 判断文件是否为dicom文件
dcm = pydicom.dcmread(os.path.join(PathName, filename))
#直接从dcm读出的像素矩阵
img_arr = dcm.pixel_array
img_arr.dtype = "int16"
print(img_arr) #打印img_arr
#CT值的单位是Hounsfield,简称为Hu,范围是-1024-3071。用于衡量人体组织对X射线的吸收率,设定水的吸收率为0Hu。
# 在DICOM图像读取的过程中,我们会发现图像的像素值有可能不是这个范围,通常是0-4096,这是我们常见到的像素值或者灰度值,这就需要我们在图像像素值(灰度值)转换为CT值。
# 首先,需要读取两个DICOM Tag信息,(0028|1052):rescale intercept和(0028|1053):rescale slope.
# 然后通过公式:
# Hu = pixel * slope + intercept
# 计算得到CT值。
# 利用公式将像素值转为CT值,Hu = pixel * slope + intercept
for i in range(img_arr.shape[0]):
for j in range(img_arr.shape[1]):
img_arr[i][j] = img_arr[i][j] * slope + intercept
print(img_arr)
#利用阈值转为二值图
for i in range(img_arr.shape[0]):
for j in range(img_arr.shape[1]):
if img_arr[i][j] >= 662 and img_arr[i][j] <= 1988:
img_arr[i][j] = 255
else:
img_arr[i][j] = 0
print(img_arr)
file_name1 = os.path.splitext(filename)[0] # 只要文件名字,去掉扩展名
#print(file_name1)
#output_file = os.path.join(OutputFile, file_name1)
#output_file1 = output_file + ".jpg" # 要带上存储图片的扩展名,不然写不进去
output_file1 = "./1/" + file_name1 + ".jpg"
print(output_file1)
if cv2.imwrite(output_file1, img_arr):
print("ok")
else:
print("faulse")
print("all transformed")