【检查nii文件所有的像素值是否有小于零的情况,使用GPU判断,多线程】

检查nii文件所有的像素值是否有小于零的情况,使用GPU判断,多线程

在从采样之后为了防止像素中存在小于0的值,负值,会造成数据归一化之后背景不等于0的情况,所以需要检查。

import torch
import torch.nn.functional as F
import nibabel as nib
import numpy as np
import threading
import time
import psutil
import os
import subprocess
import numpy
import torch
from torch import nn
from d2l import torch as d2l


def check(filename,folder_path):
    # Move tensors to the GPU device
    nifti_path = os.path.join(folder_path, filename)
    image = nib.load(nifti_path)

    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    tensor = torch.from_numpy(image.get_fdata()).unsqueeze(0).unsqueeze(0).float().to(device)

    # Calculate the resize factor
    has_negative = torch.any(tensor < 0).item()
    if has_negative==False:
        print(str(nifti_path)+" False")
    else:
        print(str(nifti_path)+" has value smaller than zero")


# Define the directory containing the folders of NIfTI files
input_dir = r"D:\BaiduNetdiskDownload\Breast_data\A_Yunzhong"
# Iterate over the folders in the input directory

for foldername in os.listdir(input_dir):
    folder_path = os.path.join(input_dir, foldername)
    if os.path.isdir(folder_path):
        # Create a corresponding output folder
        # Iterate over the NIfTI files in the current folder
        for filename in os.listdir(folder_path):
            if filename.endswith(".nii") or filename.endswith(".nii.gz"):
                # Load the NIfTI image
                t=threading.Thread(name="check:"+str(foldername)+str(filename),target=check,args=(filename,folder_path))
                t.start()
                time.sleep(0.3)
                while True:
                    mem = psutil.virtual_memory()
                                # 系统总计内存
                    zj = float(mem.total) / 1024 / 1024 / 1024
                                # 系统已经使用内存
                    ysy = float(mem.used) / 1024 / 1024 / 1024
                                # 系统空闲内存
                    kx = float(mem.free) / 1024 / 1024 / 1024
                    #print('系统总计内存:%d.3GB' % zj)
                    #print('系统已经使用内存:%d.3 GB' % ysy)
                    #print('系统空闲内存:%d.3GB' % kx)
                    if ysy<=12:
                        #print("start threading:"+str(foldername)+str(filename))
                        break
                    else:
                        #print('waiting')
                        time.sleep(0.1)
                # Perform resampling

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值