File size: 4,265 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
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')
    data_paths=glob.glob(r'C:\Users\zhang\PycharmProjects\mmsegmentation\data\Task02_Heart\imagesTr\*.nii.gz')
    for i,path in enumerate(image_paths):
        folder = 'mri_z_precise_train_2d'
        filename = path.split('\\')[-1].split('.')[0].replace('label', 'image')

        print(filename)
        # 获取image,转换成合适的维度
        image = nib.load(path).dataobj
        data=nib.load(data_paths[i]).dataobj
        image = np.array(image, dtype=np.int8)
        image = np.swapaxes(image, 1, 2)
        image = np.swapaxes(image, 0, 1)
        data = np.swapaxes(data, 1, 2)
        data = np.swapaxes(data, 0, 1)
        print(np.min(data),np.max(data))
        data=((data-np.min(data))/(np.max(data)-np.min(data)))*255
        data=np.array(data,dtype=int)
        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()

        indices=[]
        ranges=[128,128,320,320,320,320]
        for i in range(len(label)):
            indices.append(int(label[i]*ranges[i]))
        print(indices)

        image = nib.load(path).dataobj
        image = np.array(image, dtype=np.int8)
        image = np.swapaxes(image, 1, 2)
        image = np.swapaxes(image, 0, 1)

        # label_nii=image[indices[0]:indices[1],indices[2]:indices[3],indices[4]:indices[5]]
        # print(np.unique(label_nii))
        # data_nii=data[indices[0]:indices[1],indices[2]:indices[3],indices[4]:indices[5]]
        label_nii=image[indices[0]:indices[1],:]
        # print(np.unique(label_nii))
        data_nii=data[indices[0]:indices[1],:]

        for i in range(label_nii.shape[0]):
            cv2.imwrite(os.path.join(f'{folder}/label', f'{filename}_{i}.png'), label_nii[i,:, :])
            # print(np.unique(label_nii[i, :, :]))
        for i in range(len(data_nii)):
            cv2.imwrite(os.path.join(f'{folder}/image', f'{filename}_{i}.png'), data_nii[i,:, :])

    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
if __name__ == '__main__':
    handle_image_and_label()