根据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}")

### 使用 Vision Transformer (ViT) 模型实现医学图像二分类任务 #### 数据预处理 对于医学图像数据集,确保所有图片尺寸一致非常重要。由于ViT模型主要用于二维图像,在处理三维医学影像时需特别注意。可以考虑将3D体素转换为多个2D切片或将整个3D体积作为输入传递给改进后的ViT架构如VIT-V-Net[^2]。 ```python import numpy as np from PIL import Image import torch from torchvision.transforms import Compose, Resize, ToTensor def preprocess_image(image_path): transform = Compose([ Resize((224, 224)), # 调整大小至适合ViT输入的分辨率 ToTensor() # 将PIL图像转为PyTorch张量并归一化到[0., 1.]范围 ]) image = Image.open(image_path).convert('RGB') tensor = transform(image) return tensor.unsqueeze(0) # 添加批次维度 ``` #### 加载预训练 ViT 模型 利用现有的预训练权重初始化ViT有助于加速收敛过程,并可能提高最终模型的表现力。这里以Hugging Face Transformers库为例展示加载方式: ```python from transformers import ViTFeatureExtractor, ViTForImageClassification feature_extractor = ViTFeatureExtractor.from_pretrained('google/vit-base-patch16-224-in21k') model = ViTForImageClassification.from_pretrained('google/vit-base-patch16-224-in21k', num_labels=2) # 设置模型为评估模式(如果仅做预测) model.eval() ``` #### 修改最后一层适应特定任务需求 为了使ViT适用于具体的二分类问题,需要调整最后几层神经元的数量以及激活函数的选择。通常情况下会移除原有的全连接层,并替换成新的具有两个输出节点的新一层,分别代表两类标签的概率分布。 ```python from torch.nn import Linear, LogSoftmax num_features = model.classifier.in_features model.classifier = Linear(num_features, 2) output_activation = LogSoftmax(dim=-1) ``` #### 训练与验证流程 定义损失函数、优化器之后即可开始迭代更新参数直至满足停止条件;期间还需定期保存最佳版本以便后续部署使用。 ```python criterion = torch.nn.CrossEntropyLoss() optimizer = torch.optim.AdamW(model.parameters(), lr=5e-5) for epoch in range(num_epochs): running_loss = 0.0 for inputs, labels in train_loader: optimizer.zero_grad() outputs = model(inputs)['logits'] loss = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.item() print(f'Epoch {epoch}, Loss: {running_loss/len(train_loader)}') torch.save(model.state_dict(), 'best_model.pth') ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值