介绍

  • .dcm文件是一种医学上用于存储CT、核磁共振等成像方式得到的患者器官图像的文件格式
  • .nii.gz是通过标注软件导出的3D标签(可以看作一个np数组)

我们通过pydicom和nibabel这两个包来辅助我们进行操作

  1. 读取dcm数据并用plt显示

# 读取dcm数据并使用plt显示# ······································ #
fpath = ""
ds = pydicom.dcmread(fpath)
new_image = ds.pixel_array
scaled_image = (np.maximum(new_image, 0) / new_image.max()) * 255.0
plt.figure(figsize=(10, 10))
plt.imshow(scaled_image, cmap=plt.cm.bone)
plt.show()
print(scaled_image.max())
# ······································ #
  1. 批量处理.dcm文件,将其转化为.png格式:
def dcm_to_image(filepath, aimfile):fpath = os.listdir(filepath)for f in fpath:if f[-4:] != ".dcm":continueimg_path = os.path.join(filepath, f)img = pydicom.dcmread(img_path)img_data = img.pixel_array# dcm的值转化为0 ~ 255之间img_data = (np.maximum(img_data, 0) / img_data.max()) * 255.0# 开始转换为图像fname = f.replace('.dcm', '')  # 去掉nii的后缀名print(fname)imageio.imwrite(os.path.join(aimfile, fname + '.png'), img_data)
  1. 批量处理.nii.gz文件,将其转化为.png格式:
def nii_to_image(filepath, imgfile):filenames = os.listdir(filepath)  # 读取nii文件夹slice_trans = []for f in filenames:# 开始读取nii文件if f[-7:] != ".nii.gz":continueimg_path = os.path.join(filepath, f)img = nib.load(img_path)  # 读取niiimg_fdata = img.get_fdata()fname = f.replace('.nii.gz', '')  # 去掉nii的后缀名img_f_path = os.path.join(imgfile, fname)# 创建nii对应的图像的文件夹if not os.path.exists(img_f_path):os.mkdir(img_f_path)  # 新建文件夹# 开始转换为图像(x, y, z) = img.shapefor i in range(z):  # z是图像的序列silce = img_fdata[:, :, i]  # 选择哪个方向的切片都可以silce = silce.transpose()imageio.imwrite(os.path.join(img_f_path, '{}.png'.format(i)), silce)# 保存图像