File size: 5,532 Bytes
371ecdf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import cv2
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as func
from captum.attr import IntegratedGradients
import __main__


class ConvNet(nn.Module):
    def __init__(self):
        super().__init__()

        # размер исходной картинки 180x180

        self.conv1 = nn.Conv2d(3, 8, 3, padding=1)
        self.batchnorm1 = nn.BatchNorm2d(8)
        self.pool1 = nn.MaxPool2d((2, 2))

        self.conv2 = nn.Conv2d(8, 16, 8, padding=1)
        self.dropout2 = nn.Dropout(0.25)

        self.batchnorm2 = nn.BatchNorm2d(16)
        self.pool2 = nn.MaxPool2d((2, 2))

        self.conv3 = nn.Conv2d(16, 32, 2, padding=1)
        self.dropout3 = nn.Dropout(0.25)
        self.batchnorm3 = nn.BatchNorm2d(32)
        self.pool3 = nn.MaxPool2d((2, 2))

        self.conv4 = nn.Conv2d(32, 16, 16, padding=1)
        self.dropout4 = nn.Dropout(0.25)
        self.batchnorm4 = nn.BatchNorm2d(16)

        # flatten
        self.flatten = nn.Flatten()

        self.fc_2_1 = nn.Linear(28224, 512)
        self.fc_2_2 = nn.Linear(512, 4)

        # linear 1
        self.fc1 = nn.Linear(1024, 512)
        self.fc2 = nn.Linear(512, 4)

    def forward(self, x):
        x = func.relu(self.conv1(x))
        x = self.batchnorm1(x)
        x = self.pool1(x)

        x = func.relu(self.conv2(x))
        x = self.dropout2(x)
        x = self.batchnorm2(x)
        x = self.pool2(x)

        x_1 = func.relu(self.conv3(x))
        x_1 = self.dropout3(x_1)
        x_1 = self.batchnorm3(x_1)
        x_1 = self.pool3(x_1)

        x_1 = func.relu(self.conv4(x_1))
        x_1 = self.dropout4(x_1)
        x_1 = self.batchnorm4(x_1)

        x_1 = self.flatten(x_1)
        x_1 = func.relu(self.fc1(x_1))
        x_1 = self.fc2(x_1)

        x_2 = self.flatten(x)
        x_2 = func.relu(self.fc_2_1(x_2))
        x_2 = self.fc_2_2(x_2)

        return x_1 + x_2


setattr(__main__, "ConvNet", ConvNet)

device = 'cpu'
model_ = torch.load('model_5_7_14_27_0.993125_final')
model_.eval()


def get_class_of_demension(idx):
    classes = ['NonDemented', 'VeryMildDemented', 'MildDemented', 'ModerateDemented']
    return classes[idx]


def get_segmented_map(image_attr: np.array,
                      color_map: str = 'positive',
                      borders: tuple = (20, 20)) -> np.array:
    """arg: color_map: [positive, all]"""
    if color_map != 'all':
        for i in range(len(image_attr)):
            for j in range(len(image_attr[i])):
                flag_zero = False
                if color_map == 'positive':
                    if max(image_attr[i][j]) != image_attr[i][j][1]:
                        flag_zero = True
                    else:
                        if sum(image_attr[i][j]) - max(image_attr[i][j]) > borders[1]:
                            flag_zero = True
                elif color_map == 'negative':
                    if max(image_attr[i][j]) == image_attr[i][j][1] or max(image_attr[i][j]) == image_attr[i][j][2]:
                        flag_zero = True
                    else:
                        if sum(image_attr[i][j]) - max(image_attr[i][j]) > borders[0]:
                            flag_zero = True
                if flag_zero:
                    image_attr[i][j] = [0, 0, 0]
    return image_attr


def show_pack_of_images(images, labels):
    f, axes = plt.subplots(1, len(images), figsize=(30, 5))
    for i, axis in enumerate(axes):
        img = images[i]
        axes[i].imshow(img)
        axes[i].set_title(labels[i])
    plt.show()


def create_color_map_igrad(net, img_path: str) -> tuple:
    integrated_gradients = IntegratedGradients(net)
    img = cv2.cvtColor(cv2.resize(cv2.imread(img_path, 0), (180, 180)), cv2.COLOR_GRAY2RGB)
    img_tensor = torch.from_numpy(np.array(img).astype(np.float32)).to('cpu')
    img_tensor = img_tensor.permute(2, 0, 1) / 255
    img_tensor = img_tensor.unsqueeze(0)

    output = model_(img_tensor)
    prob = func.sigmoid(output)
    probability = float(np.max(prob.detach().numpy()))
    prediction_score, pred_label_idx = torch.topk(output, 1)
    pred_label_idx.squeeze_()
    predicted_label = pred_label_idx.item()

    attributions_ig = integrated_gradients.attribute(img_tensor, target=pred_label_idx, n_steps=200)

    imgs = [(img_tensor.squeeze().permute(1, 2, 0).cpu().numpy() * 255).astype(np.uint8),
            (np.transpose(attributions_ig.squeeze().cpu().detach().numpy(), (1, 2, 0)) * 255).astype(np.uint8)]
    imgs.extend([get_segmented_map(imgs[1].copy(), 'negative'), get_segmented_map(imgs[1].copy(), 'positive')])
    labels = [get_class_of_demension(predicted_label), 'all', 'negative', 'positive']

    return imgs, labels, probability


def get_results_model(image_path, model):
    images, labels, probability = create_color_map_igrad(model, image_path)

    img = images[3].copy()
    original = images[0].copy()

    result = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY);
    result = cv2.blur(result, (5, 5));

    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    ret, result = cv2.threshold(result, 0.3 * max_val, 255, cv2.THRESH_BINARY)

    contours, hierarchy = cv2.findContours(result, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)

    for element in contours:
        if 150 > len(element) > 35:
            color = (255, 0, 0)
            x, y, w, h = cv2.boundingRect(element)
            cv2.rectangle(original, (x - 2, y - 2), (x + w + 1, y + h + 1), color, 1)

    return original, labels[0], probability