当前位置: 移动技术网 > IT编程>脚本编程>Python > python 读取dicom文件,生成info.txt和raw文件的方法

python 读取dicom文件,生成info.txt和raw文件的方法

2019年03月20日  | 移动技术网IT编程  | 我要评论

木吉他独奏,类似nuvid,夏华秋叶

目标:利用python读取dicom文件,并进行处理生成info.txt和raw文件

实现:通过pydicom读取dicom文件

代码:

import numpy
import pydicom
import os

# dicom文件所在的文件夹目录
pathdicom = '/home/lk/testdata/1.3.6.1.4.1.9328.50.1.42697596859477567872763647333745089432/'

# 筛选出文件夹目录下所有的dicom文件
lstfilesdcm = []
for dirname, subdirlist, filelist in os.walk(pathdicom):
  for filename in filelist:
    if '.dcm' in filename.lower():
      lstfilesdcm.append(os.path.join(dirname, filename))

# get ref file
refds = pydicom.read_file(lstfilesdcm[0])

# load dimensions based on the number of rows, columns, and slices (along the z axis)
constpixeldims = (int(refds.rows), int(refds.columns), len(lstfilesdcm))

# load spacing values (in mm)
constpixelspacing = (float(refds.pixelspacing[0]), float(refds.pixelspacing[1]), float(refds.slicethickness))

# save info.txt
info = constpixeldims + constpixelspacing
f = open('/home/lk/testdata/1.3.6.1.4.1.9328.50.1.42697596859477567872763647333745089432/info.txt', 'w')
for n in info:
  f.write(str(n)+' ')
f.close()


# according to location sorting
location = []
for i in range(len(lstfilesdcm)):
  ds = pydicom.read_file(lstfilesdcm[i])
  location.append(ds.slicelocation)
location.sort()

# the array is sized based on 'constpixeldims'
arraydicom = numpy.zeros((len(lstfilesdcm), refds.rows, refds.columns), dtype=refds.pixel_array.dtype)

# loop through all the dicom files
for filenamedcm in lstfilesdcm:
  # read the file
  ds = pydicom.read_file(filenamedcm)
  # store the raw image data
  arraydicom[location.index(ds.slicelocation), :, :] = ds.pixel_array

# save raw
ds = arraydicom.tostring()
f = open('/home/lk/testdata/1.3.6.1.4.1.9328.50.1.42697596859477567872763647333745089432/1.raw', 'wb')
f.write(ds)
f.close()

代码编写过程遇到的问题及解决方法:

problem one: pydicom版本问题。

pydicom1.x中读取dicom文件调用pydicom.read_file(filename);

pydicom0.9中读取dicom文件调用dicom.read_file(filename);

problem two:python中io操作

(1) f = open(filename, mode)

其中filename为文件的路径, mode为操作标识符:‘r' 表示读, ‘w'表示写,‘a'表示既可读又可写,‘b'表示二进制文件。

(2) f.write(value)

其中参数value必须是字符串类型的。

当然还有一些其他的问题,在这里就不细说了,多入坑才能学的多,切不可烦躁,代码就是要多敲才能得心应手,共勉。

以上这篇python 读取dicom文件,生成info.txt和raw文件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网