#dcm转二值图(阈值可调)
import pydicom
import numpy as np
import os
import cv2
np.set_printoptions(threshold=np.inf)
PathDicom = 'E:\\1thx\\preprocessJPG\\adddcm' # 存放的dcm文件路径
#OutputFile = "E:\\2_DicomPython\\dicom代码\\DcmtoBinaryjpg\\DcmtoBinary"
#从dcm文件中读出slope和intercept 一般分别为1和-1024 这里直接省略
#dcm = pydicom.read_file(PathDicom+"\\12531097-Thorax^03_Thorax_Rib (Adult)-2022-01-30_0005_0154_752564566.dcm")
#slope = dcm.RescaleSlope #1
#intercept = dcm.RescaleIntercept #-1024
slope = 1
intercept = -1024
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: #骨头
#if img_arr[i][j] >= -5 and img_arr[i][j] <= 135: #肌肉组织
img_arr[i][j] = 255
else:
img_arr[i][j] = 0
#print(img_arr)
file_name1 = os.path.splitext(filename)[0] # 只要文件名字,去掉扩展名
if cv2.imwrite("E:\\1thx\\preprocessJPG\\binary\\" + file_name1 + ".jpg", img_arr):
print("ok")
#print(img_arr.shape)
else:
print("faulse")
print("all transformed")
Python dcm转二值图JPG(阈值可调)
于 2022-04-22 11:31:12 首次发布