-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidation.py
190 lines (151 loc) · 7.19 KB
/
validation.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
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import argparse
import os
import parser
from glob import glob
import matplotlib.pyplot as plt
import numpy as np
import cv2
import torch
import torch.backends.cudnn as cudnn
import torch.nn.functional as F
import yaml
import albumentations as A
from albumentations.core.composition import Compose
from sklearn.model_selection import train_test_split
from tqdm import tqdm
from PIL import Image
import archs
from dataset import Dataset
from metrics import iou_score
from utils import AverageMeter
import colorsys
"""
需要指定参数:--name project name
"""
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--name', default="project name",
help='model name')
parser.add_argument('--num_classes', default=4, type=int,
help='number of classes')
args = parser.parse_args()
return args
def main():
args = parse_args()
with open('models/%s/config.yml' % args.name, 'r') as f:
config = yaml.load(f, Loader=yaml.FullLoader)
print('-' * 20)
for key in config.keys():
print('%s: %s' % (key, str(config[key])))
print('-' * 20)
cudnn.benchmark = True
# create model
print("=> creating model %s" % config['arch'])
model = archs.__dict__[config['arch']](config['num_classes'],
config['input_channels'],
config['deep_supervision'])
model = model.cuda()
model.load_state_dict(torch.load('models/%s/model-X.pth' %
config['name']))
model.eval()
inputdir = r'C:\Users\Data'
# Data loading code
img_ids = glob(os.path.join(inputdir, config['dataset'], 'GFP_original', '*' + config['img_ext']))
img_ids = [os.path.splitext(os.path.basename(p))[0] for p in img_ids]
_, val_img_ids = train_test_split(img_ids, test_size=0.15, random_state=45)
# model.load_state_dict(torch.load('models/%s/model.pth' %
# config['name']))
# model.eval()
val_transform = A.Compose([
A.ToFloat(max_value=1.0),
#A.Resize(config['input_h'], config['input_w']),
#A.Normalize(mean=(0.03684), std=(0.01488), max_pixel_value=1),
# A.FromFloat(max_value=13108.0)
])
val_dataset = Dataset(
img_ids=val_img_ids,
img_dir=os.path.join(inputdir, config['dataset'], 'GFP_original'),
mask_dir=os.path.join(inputdir, config['dataset'], 'groundtruth_unet++'),
img_ext=config['img_ext'],
mask_ext=config['mask_ext'],
num_classes=config['num_classes'],
transform=val_transform)
val_loader = torch.utils.data.DataLoader(
val_dataset,
batch_size=config['batch_size'],
shuffle=False,
num_workers=config['num_workers'],
drop_last=False)
avg_meter = AverageMeter()
os.makedirs(os.path.join('outputs', config['name'], 'png_results'), exist_ok=True)
# for c in range(config['num_classes']):
# os.makedirs(os.path.join('outputs', config['name'], str(c)), exist_ok=True)
with torch.no_grad():
for input, target, meta in tqdm(val_loader, total=len(val_loader)):
input = input.cuda()
target = target.cuda()
outimage = []
# compute output
if config['deep_supervision']:
output = model(input)[-1]
else:
output = model(input)
iou = iou_score(output, target)
avg_meter.update(iou, input.size(0))
# output = torch.sigmoid(output).cpu().numpy()
#
pr_soft_last = F.softmax(output.permute(0, 2, 3, 1), dim=-1).cpu().numpy()
pr_soft_last_arg = pr_soft_last.argmax(axis=-1)
colors = [(0, 0, 0), (128, 0, 0), (0, 128, 0), (128, 128, 0), (0, 0, 128), (128, 0, 128), (0, 128, 128),
(128, 128, 128), (64, 0, 0), (192, 0, 0), (64, 128, 0), (192, 128, 0), (64, 0, 128),
(192, 0, 128),
(64, 128, 128), (192, 128, 128), (0, 64, 0), (128, 64, 0), (0, 192, 0), (128, 192, 0),
(0, 64, 128),
(128, 64, 12)]
for i in range(np.shape(pr_soft_last_arg)[0]):
seg_img = np.zeros((np.shape(pr_soft_last_arg)[0],
np.shape(pr_soft_last_arg)[1],
np.shape(pr_soft_last_arg)[2], 3))
# ---------------------
# 需要注意的是:cv写图像的时候也是按照BRG,与RGB不一样,因此是需要调整顺序才能获得正确颜色
# ---------------------
for c in range(4):
seg_img[i, :, :, 0] += (
(pr_soft_last_arg[i, :, :] == c) * (colors[c][2])).astype('uint8')
seg_img[i, :, :, 1] += (
(pr_soft_last_arg[i, :, :] == c) * (colors[c][0])).astype('uint8')
seg_img[i, :, :, 2] += (
(pr_soft_last_arg[i, :, :] == c) * (colors[c][1])).astype('uint8')
seggg = seg_img[i]
#seggg = cv2.resize(seggg, (1200, 1200), interpolation=cv2.INTER_LINEAR)
cv2.imwrite(os.path.join('outputs', config['name'], meta['img_id'][i] + '.jpg'),
seggg.astype('uint8'))
segggr = pr_soft_last_arg[i]
#segggr = cv2.resize(segggr, (1200, 1200), interpolation=cv2.INTER_NEAREST_EXACT)
cv2.imwrite(os.path.join('outputs', config['name'],'png_results', meta['img_id'][i] + '.png'),
segggr.astype('uint8'))
# ------------------------------------------------#
# 将新图片转换成Image的形式
# ------------------------------------------------#
# for i in range(len(outimage)):
# cv2.imwrite(os.path.join('outputs', config['name'], meta['img_id'][i] + '.jpg'),
# (np.array(i * 255).astype('uint8')))
print('IoU: %.4f' % avg_meter.avg)
# plot_examples(input, target, model,num_examples=3)
torch.cuda.empty_cache()
#
# def plot_examples(datax, datay, model,num_examples=6):
# fig, ax = plt.subplots(nrows=num_examples, ncols=3, figsize=(18,4*num_examples))
# m = datax.shape[0]
# for row_num in range(num_examples):
# image_indx = np.random.randint(m)
# image_arr = model(datax[image_indx:image_indx+1]).squeeze(0).detach().cpu().numpy()
# ax[row_num][0].imshow(np.transpose(datax[image_indx].cpu().numpy(), (1,2,0))[:,:,0])
# ax[row_num][0].set_title("Orignal Image")
# ax[row_num][1].imshow(np.squeeze((image_arr > 0.40)[0,:,:].astype(int)))
# ax[row_num][1].set_title("Segmented Image localization")
# ax[row_num][2].imshow(np.transpose(datay[image_indx].cpu().numpy(), (1,2,0))[:,:,0])
# ax[row_num][2].set_title("Target image")
# plt.show()
if __name__ == '__main__':
main()