File size: 5,497 Bytes
1c40643 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 |
import sys
import cv2
import matplotlib.pyplot as plt
import nibabel as nib
import os
import glob
# from scipy.ndimage import zoom
import numpy as np
import skimage.transform
import torch.optim
from skimage import transform
from scipy.ndimage import binary_fill_holes, zoom
from scipy.ndimage import map_coordinates
from vnet import VNet
from half_vnet import HalfVNet
from torch.utils.data import Dataset, DataLoader
import torch.nn as nn
from torch.optim import AdamW
from torch.cuda.amp import GradScaler
from torch.cuda.amp import autocast
from tqdm import tqdm
def handle_image_and_label():
cnt = 0
pos_label = []
image_paths = glob.glob(r'C:\Users\zhang\PycharmProjects\mmsegmentation\data\Task02_Heart\labelsTr\*.nii.gz')
for path in image_paths:
folder = 'mri_train_2d1'
filename = path.split('\\')[-1].split('.')[0].replace('label', 'image')
print(filename)
# 获取image,转换成合适的维度
image = nib.load(path).dataobj
image = np.array(image, dtype=np.int8)
image = np.swapaxes(image, 1, 2)
image = np.swapaxes(image, 0, 1)
D, H, W = image.shape
plt.subplot(1, 3, 1)
plt.imshow(image[60, :, :])
image = transform.resize(image, (128, 320, 320))
plt.subplot(1, 3, 2)
plt.imshow(image[60, :, :])
# 获取归一化的坐标
z_min, z_max = get_min_and_max_by_axis(image, 0)
x_min, x_max = get_min_and_max_by_axis(image, 1)
y_min, y_max = get_min_and_max_by_axis(image, 2)
label = [z_min, z_max, x_min, x_max, y_min, y_max]
print(image.shape, label)
pos_label.append(label)
image = transform.resize(image, (D, 320, 320))
plt.subplot(1, 3, 3)
plt.imshow(image[60, :, :])
plt.show()
pos_label = np.array(pos_label)
print(pos_label.shape)
np.save('./imagesTr/pos_labels.npy', pos_label)
def get_min_and_max_by_axis(image, axis, eps=1e-2):
label_list = []
length = image.shape[axis]
if axis == 0:
for i in range(length):
if len(np.unique(image[i, :, :])) != 1:
label_list.append(i)
elif axis == 1:
for i in range(length):
if len(np.unique(image[:, i, :])) != 1:
label_list.append(i)
elif axis == 2:
for i in range(length):
if len(np.unique(image[:, :, i])) != 1:
label_list.append(i)
norm_min, norm_max = min(label_list) / length - eps, max(label_list) / length + eps
print(min(label_list), int(norm_min * length), max(label_list), int(norm_max * length))
return norm_min, norm_max
class NIIDataset(Dataset):
def __init__(self, path,resize_shape):
super().__init__()
self.image_paths = glob.glob(path)
label_path=path[:-8]+'pos_labels.npy'
self.labels=np.load(label_path)
self.resize_shape=resize_shape
def __len__(self):
return len(self.image_paths)
def __getitem__(self, index):
image=np.array(nib.load(self.image_paths[index]).dataobj)
image=transform.resize(image,output_shape=self.resize_shape)[np.newaxis,:]
label=self.labels[index]
return image,label
if __name__ == '__main__':
# handle_image_and_label()
dataset = NIIDataset(path='./imagesTr/*.nii.gz',resize_shape=(128,320,320))
dataloader=DataLoader(dataset,batch_size=2,shuffle=True)
test_dataloader=DataLoader(dataset,batch_size=1)
device="cuda" if torch.cuda.is_available() else "cpu"
print(device)
model=HalfVNet().to(device)
criterion=torch.nn.L1Loss(reduction='sum').to(device)
optimizer=torch.optim.AdamW(model.parameters(),lr=0.001)
scaler=GradScaler()
EPOCHS=100
# weights=torch.load('./weights/vnet_100.pth')
# model.load_state_dict(weights)
TRAIN=True
TEST=True
if TRAIN:
for epoch in range(1,EPOCHS+1):
model.train()
losses=[]
train_bar=tqdm(dataloader,file=sys.stdout)
for step,(images,labels) in enumerate(train_bar):
with autocast():
images=images.to(device)
labels=labels.to(torch.float32).to(device)
output=model(images)
optimizer.zero_grad()
loss=criterion(output,labels)
# loss.backward()
# optimizer.step()
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
losses.append(loss.item())
# print(f"epoch:{epoch},mean loss:{sum(losses)/len(losses)}")
train_bar.set_postfix(epoch=epoch,step=step,step_loss=loss.item(),mean_loss=sum(losses)/len(losses))
if epoch%10==0:
torch.save(model.state_dict(),f'./weights/vnet_{epoch}.pth')
if TEST:
weights=torch.load('./weights/vnet_100.pth')
model.load_state_dict(weights)
model.eval()
for step,(images,labels) in enumerate(dataloader):
with autocast():
images = images.to(device)
labels = labels.to(torch.float32).to(device)
output = model(images)
print("labels:",labels)
print("predicts:",output) |