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)
【代码】将dcm和nii.gz文件转为h5文件
于 2022-03-31 21:52:45 首次发布