python 图像处理 医学图像格式 - center = 40
医学影像学习(二)
1.NIFTI格式
大部分医学领域导出dicom格式,但是太复杂了。很多时候,将dicom转换为nifti格式也就是nii格式。
1.1包含内容
标准nifti图像的拓展名是.nii,包含了头文件及图像资料,一个NIFTI格式主要包含三部分:header,extension,image。
1.1.1header
这部分数据长度是固定的,当然不同版本可能规定的长度不同,但是同一版本的多个nii文件是相同的。
包含:
维度:x,y,z单位毫米,还有第四个维度时间
voxel size(体素大小):毫米单位的x,y,z大小
数据类型:一般是int16,这个精度不够,最好使用double类型
Form和转换矩阵:每一个Form都对应一个转换矩阵。
Nifti 格式使用 RAS (Right, Anterior, Superior) 作为坐标系的正方向.
1.1.2extension
自己定义数据的部分
1.1.3image
存储3D或者4D的图像数据
1.2特点
NIFTI中一个主要的特点在于它包含了两个仿射坐标定义,这两个仿射坐标定义能够将每个立体元素指标(i,j,k)和空间位置(x,y,z)联系起来
.nii格式相对与dicom处理起来更快
1.3.nii格式与.nii.gz格式
事实上:nii格式和.nii.gz格式是一个东西。
1.4读写工具
Nibabel是用于读取nifti文件的一个Python库
2.dicom格式
DICOM 代表的是医疗数字成像和通信,CT图像的格式是.dicom,可以用pydicom进行处理,其含有许多的DICOM Tag信息
一张CT图像有 512x512 个像素点,在dicom文件中每个像素由2字节表示,所以每张图片约512KB大小。
2.1内容
一个 DICOM 文件包含文件头部和同文件名的*.dcm 图像数据。文件头部的大小取决于它所提供的信息的多少。文件头包含以下信息:病人的 ID,病人的姓名,图像的模态以及其他信息。它定义了帧的数量以及图像的精度,事实上每一张dicom图像都带有大量图片信息
由以下代码可以获取文件头部信息和图片信息
import pydicom as dicom
DATA_PATH = "C:\\Users\\23202\\Desktop\\Postgraduatestudy\\Simple_of_Spinal_CT\\liu_xin_dicom"
#获取Dicom文件信息说明
f = dicom.read_file(DATA_PATH + '/liu_xin_0000.dcm')
print(f)
importSimpleITK as sitk
import matplotlib.pyplot as plt
#获取Dicom数据
ds = sitk.ReadImage(DATA_PATH+'/liu_xin_0000.dcm')
img_array = sitk.GetArrayFromImage(ds)
print(img_array.shape)
plt.imshow(img_array[0],cmap="gray")
plt.show()
使用pydicom库获得文件头部信息如下:
可以看到
每一个DICOM Tag都是由两个十六进制数的组合来确定的,分别为Group和Element。
例如一般0010开头的为患者的私人隐私信息包括姓名,出生日期等
使用SimpleITK读取图片信息如下
2.2工具
pydicom是一个读取 dicom 文件的 python 库
3..dicom数据处理过程,使用python输出脊椎3D图像
import pydicom as dicom
import SimpleITK as sitk
import cv2
import os
import numpy as np
import matplotlib.pyplot as plt
import scipy
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from skimage import measure # 要pip的是scikit-image
import time as t
# 获取Dicom文件信息说明
def read_file(path):
f = dicom.read_file(path + '/liu_xin_0000.dcm')
print(f) 拼多多帮助力入口
print(type(f))
# print(f.SliceThickness)
# print(f.pixel_array)
print(f.ImagePositionPatient[2])
# 获取Dicom数据
def get_dicom_data(path):
ds = sitk.ReadImage(path + '/liu_xin_0000.dcm')
img_array = sitk.GetArrayFromImage(ds)
print(img_array.shape)
plt.imshow(img_array[0], cmap="gray")
plt.show()
# 运用pydicom读取dcm格式的CT图像切片的代码实现
def load_scan(path):
# 获取切片
slices = [dicom.read_file(path + '/' + s) for s in os.listdir(path)]
# 按ImagePositionPatient[2]排序,否则得到的扫描面是混乱无序的
slices.sort(key=lambda x: int(x.ImagePositionPatient[2])) # 以Z轴坐标排序
# 获取切片厚度
try:
# slice_thickness为Z轴坐标差,也即切片厚度
slice_thickness = np.abs(slices[0].ImagePositionPatient[2] - slices[1].ImagePositionPatient[2])
except:
# ImagePositionPatient为长度为3的数组[X, Y, Z]而SliceLocation仅表示Z轴位置
slice_thickness = np.abs(slices[0].SliceLocation - slices[1].SliceLocation)
for s in slices:
s.SliceThickness = slice_thickness
return slices
# 为了更好地观察不同器官,需要将像素值转换为CT值,单位为HU。
# 计算方法为HU=pixel*rescale slope+rescale intercept。
# 其中,rescale slope和rescale intercept是dicom图像文件的两个tag信息。
def get_pixels_hu(slices):
image = np.stack([s.pixel_array for s in slices])
# Convert to int16 (from sometimes int16),
# should be possible as values should always be low enough (<32k)
image = image.astype(np.int16) # image.shape = (301, 512, 512)
# Set outside-of-scan pixels to 0
# The intercept is usually -1024, so air is approximately 0
# CT扫描边界之外的灰度值是固定的,为2000,需要把这些值设置为0
image[image == -2000] = 0
# Convert to Hounsfield units (HU) 转换为HU,就是 灰度值*rescaleSlope+rescaleIntercept
for slice_number in range(len(slices)):
intercept = slices[slice_number].RescaleIntercept # -1024
slope = slices[slice_number].RescaleSlope # 1
if slope != 1:
image[slice_number] = slope * image[slice_number].astype(np.float64)
image[slice_number] = image[slice_number].astype(np.int16)
image[slice_number] += np.int16(intercept)
return np.array(image, dtype=np.int16)
def view_the_hu_distribution(path):
patient_slices = load_scan(path)
patient_pixels = get_pixels_hu(patient_slices)
plt.hist(patient_pixels.flatten(), bins=80, color='c')
plt.xlabel("Hounsfield Units (HU)")
plt.ylabel("Frequency")
plt.show()
# 将像素值转换为CT值之后,可以设置窗宽、窗位来更好地观察不同组织、器官
# 如果想观察这一特定组织,就将窗位设置为其对应的CT值,而窗宽是CT图像可以显示的CT值范围,窗位大小是窗宽上、下限的平均值。
def get_window_size(organ_name):
if organ_name == 'lung':
# 肺部 ww 1500-2000 wl -450--600
center = -500
width = 2000
elif organ_name == 'abdomen':
# 腹部 ww 300-500 wl 30-50
center = 40
width = 500
elif organ_name == 'bone':
# 骨窗 ww 1000-1500 wl 250-350
center = 300
width = 2000
elif organ_name == 'lymph':
# 淋巴、软组织 ww 300-500 wl 40-60
center = 50
width = 300
elif organ_name == 'mediastinum':
# 纵隔 ww 250-350 wl 250-350
center = 40
width = 350
return center, width
def setDicomCenWid(slices, organ_name):
img = slices
center, width = get_window_size(organ_name) # bone center = 300 width = 2000
min = (2 * center - width) / 2.0 + 0.5 # min = -700 + 0.5
max = (2 * center + width) / 2.0 + 0.5 # max = 1300 + 0.5
dFactor = 255.0 / (max - min) # dFactor = 255/2000
d, h, w = np.shape(img) # [d, h, w] = [301, 512, 512]
print(d, h, w)
for n in np.arange(d):
for i in np.arange(h):
for j in np.arange(w):
img[n, i, j] = int((img[n, i, j] - min) * dFactor)
min_index = img < 0
img[min_index] = 0
max_index = img > 255
img[max_index] = 255
return img
# CT图像不同扫描面的像素尺寸、粗细粒度是不同的,这对进行CNN有不好的影响,因此需要进行重构采样,将图像重采样为[1,1,1]
# 不同扫描面的像素尺寸,粗细粒度是不同的,这不利于我们进行CNN任务,我们可以使用同构采样。
def resample(image, slice, new_spacing=[1, 1, 1]):
# 将列表每一个数用float函数处理,返回迭代对象
spacing = map(float, ([slice.SliceThickness] + [slice.PixelSpacing[0], slice.PixelSpacing[1]]))
spacing = np.array(list(spacing)) # [0.5 0.35742188 0.35742188]
resize_factor = spacing / new_spacing # [0.5 0.35742188 0.35742188]
new_real_shape = image.shape * resize_factor # [150.5 183.00000256 183.00000256]
new_shape = np.round(new_real_shape) # 取整四舍五入[150. 183. 183.] 当数字以零结尾会向下取整
real_resize_factor = new_shape / image.shape # [0.49833887 0.35742188 0.35742188]
new_spacing = spacing / real_resize_factor
image = scipy.ndimage.interpolation.zoom(image, real_resize_factor, mode='nearest')
return image, new_spacing
# 使用matplotlib构建3D图像,一般时间较长
def plot_3d(image, threshold=-300):
# Position the scan upright,
# so the head of the patient would be at the top facing the camera
p = image.transpose(2, 1, 0) # 将扫描件竖直放置
verts, faces, _, _ = measure.marching_cubes(p, threshold) # Liner推进立方体算法来查找3D体积数据中的曲面。
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111, projection='3d')
# Fancy indexing: `verts[faces]` to generate a collection of triangles
mesh = Poly3DCollection(verts[faces], alpha=0.1) # 创建3Dpoly
face_color = [0, 0, 0] # 颜色为黑色
mesh.set_facecolor(face_color) # 设置颜色
ax.add_collection3d(mesh)
ax.set_xlim(0, p.shape[0])
ax.set_ylim(0, p.shape[1])
ax.set_zlim(0, p.shape[2])
plt.show()
if __name__ == '__main__':
start_time = t.time()
DATA_PATH = "C:\\Users\\23202\\Desktop\\Postgraduate study\\Simple_of_Spinal_CT\\liu_xin_dicom"
# load_scan(DATA_PATH)
# read_file(DATA_PATH)
# 查看病人hu分布情况
# view_the_hu_distribution(DATA_PATH)
slices = load_scan(DATA_PATH)
slices_array_hu = get_pixels_hu(slices)
img = setDicomCenWid(slices_array_hu, "bone")
pix_resampled, new_spacing = resample(img, slices[0])
# 调用函数
# 经过测试运行时间在300秒左右,threshold=125左右最明显,但实际也很粗糙,真正要查看还是得用mimics
plot_3d(pix_resampled, 125)
end_time = t.time()
print(end_time - start_time)
输出结果:
推荐链接