【代码】将dcm和nii.gz文件转为h5文件

import pydicom
import matplotlib.pyplot as plt
import numpy as np
import os
import time
import nibabel as nib
import h5py

def show_image(image1):
    plt.figure(figsize=(10, 5))

    plt.subplot(1, 1, 1)
    plt.axis('off')
    plt.imshow(image1)

    plt.show()

path = '/root/data/lak/hhh/data/pancreas'

# 读取dcm文件
def read_image(path):
    images = np.zeros((500, 512, 512))
    images_path_list = os.listdir(path)
    for id, i in enumerate(images_path_list):
        image_path = os.path.join(path, i)
        # print(image_path)
        image = pydicom.read_file(image_path).pixel_array
        images[id] = image
    return images

# 读取nii文件
def read_label(path):
    # print(path)
    labels = np.zeros((500, 512, 512))
    labelsobj = nib.load(path).dataobj
    for j in range(labelsobj.shape[2]):
        label = labelsobj[:, :, j]
        label = label.transpose()
        labels[j] = label
    return labels

if __name__ == '__main__':

    start_all_data_time = time.time()
    for idx in range(1, 83):
        images_path = os.path.join(path, 'Pancreas-CT', 'PANCREAS_{:04d}'.format(idx))
        labels_path = os.path.join(path, 'pancreas_labels', 'label{:04d}.nii.gz'.format(idx))
        # print(images_path, labels_path)
        h5_save_path = os.path.join(path, 'pancreas_h5', "imagesandlabels_{:04d}.h5".format(idx))

        images = read_image(images_path)
        labels = read_label(labels_path)

        #写入h5文件
        with h5py.File(h5_save_path, mode='w') as hf:
            hf.create_dataset(name="images", dtype=float, data=images)
            hf.create_dataset(name="labels", dtype=float, data=labels)
        print(h5_save_path)

        # break

    h5f = h5py.File(os.path.join(path, 'pancreas_h5', 'imagesandlabels_0001.h5'), mode='r')
    images = h5f['images']
    labels = h5f['labels']
    print(images.shape, labels.shape)

  • 6
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kunsir_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值