根据3D医学图像对标签进行resize

本文介绍了一个Python函数,用于调整神经影像标注文件(.nii.gz)的大小,使其与对应图像文件保持一致。使用nibabel和scipy.ndimage库进行操作,确保标签图像是按比例缩放并保持方向一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

注意:image文件名和标签文件名要对应!!!

import os
import nibabel as nib
from scipy.ndimage import zoom

def resize_label(label_img, target_shape):
    current_shape = label_img.shape
    factor = [float(t) / c for t, c in zip(target_shape, current_shape)]
    resized_label_data = zoom(label_img.get_fdata(), factor, order=0, mode='nearest')
    resized_label_img = nib.Nifti1Image(resized_label_data, affine=label_img.affine)
    # 设置调整后的标签图像的方向与原始标签图像相同
    resized_label_img.set_sform(label_img.get_sform())
    resized_label_img.set_qform(label_img.get_qform())
    return resized_label_img

# # 标签文件夹路径和图像文件夹路径
label_folder = r'lable文件夹'
image_folder = r'image文件夹'

# 遍历标签文件夹中的文件
for label_file in os.listdir(label_folder):
    if label_file.endswith('.nii.gz'):
        label_img = nib.load(os.path.join(label_folder, label_file))
        # 提取对应的图像文件路径
        image_path = os.path.join(image_folder, label_file)
        if os.path.exists(image_path):
            image_img = nib.load(image_path)
            target_shape = image_img.shape
            resized_label_img = resize_label(label_img, target_shape)
            # 保存调整大小后的标签图像
            nib.save(resized_label_img, os.path.join('文件夹', f'{label_file}'))
        else:
            print(f"Corresponding image file not found for {label_file}")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值