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

yipeiwu_com5年前Python基础

目标:利用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文件的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python3使用smtplib实现发送邮件功能

python3使用smtplib实现发送邮件功能

在之前的工作中,业务方做了一些调整,提出了对一部分核心指标做更细致的拆分并定期产出的需求。出于某些原因,这部分数据不太方便在报表上呈现,因此就考虑通过邮件的方式定期给业务方发送数据。 当...

python操作mysql中文显示乱码的解决方法

本文实例展示了一个脚本python用来转化表配置数据xml并生成相应的解析代码。 但是在中文编码上出现了乱码,现将解决方法分享出来供大家参考。 具体方法如下: 1. Python文件设置...

python类中super() 的使用解析

描述 super() 函数是用于调用父类(超类)的一个方法。 super 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序...

利用Python破解斗地主残局详解

利用Python破解斗地主残局详解

前言 相信大家都玩过斗地主,规则就不再介绍了。 直接上一张朋友圈看到的残局图: 这道题我刚看到时,曾尝试用手工来破解,每次都以为找到了农民的必胜策略时,最后都发现其实农民跑不掉。由于手...

python元组和字典的内建函数实例详解

本文实例讲述了python元祖和字典的内建函数。分享给大家供大家参考,具体如下: 元组Tuple 元组是序列类型一种,也是不可变类型数据结构,对元组修改后会生成一个新的元组。所以Tupl...