Dicom文件的读取
Pydicom
单张影像的读取
使用 pydicom.dcmread() 函数进行单张影像的读取,返回一个pydicom.dataset.FileDataset对象.
import os
import pydicom
# 调用本地的 dicom file
folder_path = r"D:\Files\Data\Materials"
file_name = "PA1_0001.dcm"
file_path = os.path.join(folder_path,file_name)
ds = pydicom.dcmread(file_path)
在一些特殊情况下,比如直接读取从医院拿到的数据(未经任何处理)时,可能会发生以下报错:
raise InvalidDicomError("File is missing DICOM File Meta Information "
pydicom.errors.InvalidDicomError: File is missing DICOM File Meta Information header or the 'DICM' prefix is missing from the header. Use force=True to force reading.
可以看到,由于缺失文件元信息头,无法直接读取,只能强行读取.这种情况可以直接根据提示,调整命令为:
ds = pydicom.dcmread(file_path,force=True)
但后续还会碰到:
AttributeError: 'Dataset' object has no attribute 'TransferSyntaxUID'
在网上检索后发现,可以通过设置TransferSyntaxUID来解决问题:
ds.file_meta.TransferSyntaxUID = pydicom.uid.ImplicitVRLittleEndian
这样就大功告成了(这里实际上就提前接触到了下面读取Dicom Tags的内容了)
一些简单处理
读取成功后,我们可以对 Dicom文件 进行一些简单的处理
读取并编辑Dicom Tags
可以通过两种方法来读取Tag的值
- 使用的Tag的Description
print(ds.PatientID,ds.StudyDate,ds.Modality)
- 使用 ds.get() 函数. 函数内参数采用的是Tag ID.几种简单的打开Dicom文件的软件(如RadiAnt DICOM Viewer)都可以直接看到.这里不再赘述.
ds.get(0x00100020) # 这里得到的是PatientID
读取到相应的Tag值后, 也可以将其他的值写入这些Tag.只要最后保存一下就可以了.