Files
python-learn/dcm2jpg.py
2024-07-05 17:29:16 +08:00

54 lines
1.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import pydicom
from PIL import Image
import numpy as np
import os
import sys
''' first: pip install pydicom matplotlib scipy '''
def dicom_file2jpg(infile, outfile):
# 读取DICOM文件
dicom_file = pydicom.read_file(infile)
info = {}
# 通过字典关键字来获取图像的数据元信息当然也可以根据TAG号
# 这里获取几种常用信息
info["PatientID"] = dicom_file.PatientID # 患者ID
info["PatientName"] = dicom_file.PatientName # 患者姓名
info["PatientAge"] = dicom_file.PatientAge # 患者年龄
info['PatientSex'] = dicom_file.PatientSex # 患者性别
info['StudyID'] = dicom_file.StudyID # 检查ID
info['StudyDate'] = dicom_file.StudyDate # 检查日期
info['StudyTime'] = dicom_file.StudyTime # 检查时间
info['InstitutionName'] = dicom_file.InstitutionName # 机构名称
info['Manufacturer'] = dicom_file.Manufacturer # 设备制造商
info['StudyDescription']=dicom_file.StudyDescription # 检查项目描述
print(info)
# 将DICOM数据转换为numpy数组
image_array = dicom_file.pixel_array
# 转换为8位图像
image_array = image_array - np.min(image_array)
image_array = image_array / np.max(image_array)
image_8bit = (image_array * 255).astype(np.uint8)
# 转换为PIL图像
image = Image.fromarray(image_8bit)
# 保存为JPEG
image.save(outfile)
def main(name):
fname = name[:-4]
outname = fname + '.jpg'
dicom_file2jpg(name, outname)
if __name__ == '__main__':
if len(sys.argv) < 2:
print('usage: python dicom_file2jpg.py dicom_filefile.dcm')
quit()
main(sys.argv[1])