Python写入DICOM文件(AttributeError: ‘FileMetaDataset’ object has no attribute ‘TransferSyntaxUID’解决方式)

写入DICOM文件

import numpy as np
import matplotlib.pyplot as plt
import pydicom
import sys

def InitDicomFile():
    infometa = pydicom.dataset.Dataset()
    infometa.TransferSyntaxUID = pydicom.uid.ImplicitVRLittleEndian
    infometa.ImplementationVersionName = 'Python ' + sys.version
    infometa.MediaStorageSOPClassUID = 'CT Image Storage'
    infometa.FileMetaInformationVersion = b'\x00\x01'
    return infometa
    
filename = r'E:\34.dcm'
# ds = pydicom.dcmread(filename) # 读取dicom图像的Tags
ds = pydicom.read_file(filename) # 读取dicom图像的Tags
info = pydicom.dataset.FileDataset({},ds) 
temp = pydicom.dcmread(filename).pixel_array # 读入DICOM图像并转化为numpy
img = temp.astype('uint16')
info.PixelData = img.tobytes()
infometa = InitDicomFile() # 一定要初始化一下否则读入会提示错误
info = pydicom.dataset.FileDataset({},info,is_implicit_VR =True, file_meta=infometa)
# info = pydicom.dataset.FileDataset({},info) # 不使用file_meta=infometa读入时会提示错误
info.save_as(r'M:\result.dcm')
# 验证新存储的DICOM可以读入
f = pydicom.dcmread(r'M:\result.dcm',force=True)
plt.imshow(f.pixel_array,'gray')
plt.show()

如果没有以下两行,读存储后的DICOM文件会提示以下错误:

infometa = InitDicomFile()
info = pydicom.dataset.FileDataset({},info,is_implicit_VR =True, file_meta=infometa)

AttributeError: ‘FileMetaDataset’ object has no attribute ‘TransferSyntaxUID’

你可能感兴趣的:(数据读写,python,dicom,图像处理)