我使用的是python3.8,
代码如下
# This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import os
import numpy as np
from PIL import Image
import nibabel as nib
# 读取PNG文件夹路径
png_folder = "F:/seg/chaos_dcm(1)/chaos_dcm/val/Ground"
# 创建保存NIfTI文件的目标文件夹
output_folder = "F:/seg/Task600-liver/label_val"
os.makedirs(output_folder, exist_ok=True)
# 遍历PNG文件夹中的所有.png文件
for filename in os.listdir(png_folder):
if filename.endswith(".png"):
png_path = os.path.join(png_folder, filename)
# 读取PNG文件并转换为灰度图像
png_image = Image.open(png_path).convert("L")
# 转换为numpy数组
png_array = np.array(png_image)
# 创建NIfTI对象
nifti_image = nib.Nifti1Image(png_array, affine=np.eye(4))
# 保存为nii.gz文件
save_path = os.path.join(output_folder, f"{filename}.nii.gz")
nib.save(nifti_image, save_path)