我试图用python3和pydicom库读取dicom文件。对于某些dicom数据,当我尝试打印pydicom.dcmread的结果时,我无法正确获取数据并收到错误消息。
但是,我尝试使用python2,它运行良好。我检查了元信息,并将其与其他可以处理的dicom文件进行了比较,我发现它们之间没有任何区别。
import pydiom
ds = pydicom.dcmread("xxxxx.dicom")
print(ds)
Traceback (most recent call last):
File "generate_train_data.py", line 387, in <module>
tf.app.run()
File "/usr/local/lib/python3.5/dist-packages/tensorflow/python/platform/app.py", line 125, in run
_sys.exit(main(argv))
File "generate_train_data.py", line 371, in main
create_ann()
File "generate_train_data.py", line 368, in create_ann
ds_ann_dir, case_name, merge_channel=False)
File "generate_train_data.py", line 290, in process_dcm_set
all_dcms, dcm_truth_infos = convert_dicoms(dcm_list, zs)
File "generate_train_data.py", line 179, in convert_dicoms
instance_num, pixel_spacing, img_np = extract_info(dcm_path)
File "generate_train_data.py", line 147, in extract_info
print(ds)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 2277-2279: ordinal not in range(128)
有人遇到过同样的问题吗?
答案 0 :(得分:0)
我相信问题的原因是Python(对我而言,它仅发生在Centos 7.6 Linux上运行的Python 3中,打印到MacOS的终端窗口上)无法弄清楚如何打印包含非字符串的字符串。 -ascii字符,因为设置了语言环境。您可以使用locale命令查看结果。我的开始是将所有内容设置为“ C”。我将LANG环境变量设置为en_US.UTF-8。这样设置对我有用。 在csh中,这是使用
完成的setenv LANG en_US.UTF-8
在bash中使用:
export LANG=en_US.UTF-8
我的问题是由“序列描述”元素中的“ µ”引起的。该文件是来自西门子扫描仪上SPECT重建的衰减图。我使用以下Python代码来帮助解决问题。
#! /usr/bin/env python3
import pydicom as dicom
from sys import exit, argv
def myprint(ds, indent=0):
"""Go through all items in the dataset and print them with custom format
Modelled after Dataset._pretty_str()
"""
dont_print = ['Pixel Data', 'File Meta Information Version']
indent_string = " " * indent
next_indent_string = " " * (indent + 1)
for data_element in ds:
if data_element.VR == "SQ": # a sequence
print(indent_string, data_element.name)
for sequence_item in data_element.value:
myprint(sequence_item, indent + 1)
print(next_indent_string + "---------")
else:
if data_element.name in dont_print:
print("""<item not printed -- in the "don't print" list>""")
else:
repr_value = repr(data_element.value)
if len(repr_value) > 50:
repr_value = repr_value[:50] + "..."
try:
print("{0:s} {1:s} = {2:s}".format(indent_string,
data_element.name,
repr_value))
except:
print(data_element.name,'****Error printing value')
for f in argv[1:]:
ds = dicom.dcmread(f)
myprint(ds, indent=1)
这是基于] 1
中的myprint函数该代码尝试打印出所有数据项。它会捕获异常并在出现错误时显示“ ****错误打印值”。
答案 1 :(得分:0)
您能举这样一个dicom文件的例子吗?在python 3.7上运行pydicom example时,它运行良好:
import matplotlib.pyplot as plt
import pydicom
from pydicom.data import get_testdata_files
filename = get_testdata_files("CT_small.dcm")[0]
ds = pydicom.dcmread(filename)
plt.imshow(ds.pixel_array, cmap=plt.cm.bone)
它还可以处理Medical Image Samples中的示例dicom文件。