forked from ternaus/angiodysplasia-segmentation
-
Notifications
You must be signed in to change notification settings - Fork 1
/
generate_masks.py
126 lines (94 loc) · 3.88 KB
/
generate_masks.py
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
"""
Script generates predictions, splitting original images into tiles, and assembling prediction back together
"""
import argparse
from prepare_train_val import get_split
from dataset import AngyodysplasiaDataset
import cv2
from models import UNet, UNet11, UNet16, AlbuNet34
import torch
from pathlib import Path
from tqdm import tqdm
import numpy as np
import utils
# import prepare_data
from torch.utils.data import DataLoader
from torch.nn import functional as F
from transforms import (ImageOnly,
Normalize,
CenterCrop,
DualCompose)
img_transform = DualCompose([
CenterCrop(512),
ImageOnly(Normalize())
])
def get_model(model_path, model_type):
"""
:param model_path:
:param model_type: 'UNet', 'UNet11', 'UNet16', 'AlbuNet34'
:return:
"""
num_classes = 1
if model_type == 'UNet11':
model = UNet11(num_classes=num_classes)
elif model_type == 'UNet16':
model = UNet16(num_classes=num_classes)
elif model_type == 'AlbuNet34':
model = AlbuNet34(num_classes=num_classes)
elif model_type == 'UNet':
model = UNet(num_classes=num_classes)
else:
model = UNet(num_classes=num_classes)
state = torch.load(str(model_path))
state = {key.replace('module.', ''): value for key, value in state['model'].items()}
model.load_state_dict(state)
if torch.cuda.is_available():
return model.cuda()
model.eval()
return model
def predict(model, from_file_names, batch_size: int, to_path):
loader = DataLoader(
dataset=AngyodysplasiaDataset(from_file_names, transform=img_transform, mode='predict'),
shuffle=False,
batch_size=batch_size,
num_workers=args.workers,
pin_memory=torch.cuda.is_available()
)
for batch_num, (inputs, paths) in enumerate(tqdm(loader, desc='Predict')):
inputs = utils.variable(inputs, volatile=True)
outputs = model(inputs)
for i, image_name in enumerate(paths):
mask = (F.sigmoid(outputs[i, 0]).data.cpu().numpy() * 255).astype(np.uint8)
h, w = mask.shape
full_mask = np.zeros((576, 576))
full_mask[32:32 + h, 32:32 + w] = mask
(to_path / args.model_type).mkdir(exist_ok=True, parents=True)
cv2.imwrite(str(to_path / args.model_type / (Path(paths[i]).stem + '.png')), full_mask)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
arg = parser.add_argument
arg('--model_path', type=str, default='data/models/UNet', help='path to model folder')
arg('--model_type', type=str, default='UNet', help='network architecture',
choices=['UNet', 'UNet11', 'UNet16', 'AlbuNet34'])
arg('--batch-size', type=int, default=4)
arg('--fold', type=int, default=-1, choices=[0, 1, 2, 3, 4, -1], help='-1: all folds')
arg('--workers', type=int, default=12)
args = parser.parse_args()
if args.fold == -1:
for fold in [0, 1, 2, 3, 4]:
_, file_names = get_split(fold)
print(len(file_names))
model = get_model(str(Path(args.model_path).joinpath('model_{fold}.pt'.format(fold=fold))),
model_type=args.model_type)
print('num file_names = {}'.format(len(file_names)))
output_path = Path(args.model_path)
output_path.mkdir(exist_ok=True, parents=True)
predict(model, file_names, args.batch_size, output_path)
else:
_, file_names = get_split(args.fold)
model = get_model(str(Path(args.model_path).joinpath('model_{fold}.pt'.format(fold=args.fold))),
model_type=args.model_type)
print('num file_names = {}'.format(len(file_names)))
output_path = Path(args.model_path)
output_path.mkdir(exist_ok=True, parents=True)
predict(model, file_names, args.batch_size, output_path)