basic_operations.py 2.23 KB
Newer Older
cc215's avatar
cc215 committed
1
2
3
4
# Created by cc215 at 27/12/19
# Enter feature description here
# Enter scenario name here
# Enter steps here
cc215's avatar
cc215 committed
5
6
import torch
import numpy as np
cc215's avatar
cc215 committed
7
8
def switch_kv_in_dict(mydict):
    switched_dict = {y: x for x, y in mydict.items()}
cc215's avatar
cc215 committed
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
    return switched_dict



def unit_normalize(d):
    d_abs_max = torch.max(
        torch.abs(d.view(d.size(0), -1)), 1, keepdim=True)[0].view(
        d.size(0), 1, 1, 1)
    # print(d_abs_max.size())
    d /= (1e-20 + d_abs_max) ## d' =d/d_max
    d /= torch.sqrt(1e-6 + torch.sum(
        torch.pow(d, 2.0), tuple(range(1, len(d.size()))), keepdim=True)) ##d'/sqrt(d'^2)
    # print(torch.norm(d.view(d.size(0), -1), dim=1))
    return d

    
def rescale_intensity(data,new_min=0,new_max=1):
    '''
    rescale pytorch batch data
    :param data: N*1*H*W
    :return: data with intensity ranging from 0 to 1
    '''
    bs, c , h, w = data.size(0),data.size(1),data.size(2), data.size(3)
cc215's avatar
cc215 committed
32
    data = data.view(bs, -1)
cc215's avatar
cc215 committed
33
34
35
    old_max = torch.max(data, dim=1, keepdim=True).values
    old_min = torch.min(data, dim=1, keepdim=True).values
    new_data = (data - old_min) / (old_max - old_min + 1e-6)*(new_max-new_min)+new_min
cc215's avatar
cc215 committed
36
    new_data = new_data.view(bs, c, h, w)
cc215's avatar
cc215 committed
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
    return new_data



def transform2tensor(cPader, img_slice,if_z_score=False):

    '''
    transform npy data to torch tensor
    :param cPader:pad image to be divided by 16
    :param img_slices: npy N*H*W
    :param label_slices:npy N*H*W
    :return: N*1*H*W
    '''
    ###
    new_img_slice = cPader(img_slice)

    ## normalize data
    new_img_slice = new_img_slice * 1.0  ##N*H*W
    new_input_mean = np.mean(new_img_slice, axis=(1, 2), keepdims=True)
    if if_z_score:
        new_img_slice -= new_input_mean
        new_std = np.std(new_img_slice, axis=(1, 2), keepdims=True)
        if abs(new_std-0)<1e-3: new_std=1
        new_img_slice /= (new_std)
    else:
        ##print ('0-1 rescaling')
        min_val = np.min(new_img_slice,axis=(1, 2), keepdims=True)
        max_val = np.max(new_img_slice,axis=(1, 2), keepdims=True)
        new_img_slice =(new_img_slice-min_val)/(max_val-min_val+1e-10)

    new_img_slice = new_img_slice[:, np.newaxis, :, :]

    ##transform to tensor
    new_image_tensor = torch.from_numpy(new_img_slice).float()
    return new_image_tensor