检查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