-
Notifications
You must be signed in to change notification settings - Fork 2
/
new_infer.py
129 lines (116 loc) · 5.24 KB
/
new_infer.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
import os
import time
import datetime
import numpy as np
import torch
from PIL import Image
from torch.autograd import Variable
from torchvision import transforms
from collections import OrderedDict
from numpy import mean
import torch.nn.functional as F
import torchvision.utils as utils
from config import *
from misc import *
import sys
import cv2
torch.manual_seed(2021)
sys.path.append('../')
from metric_caller import CalTotalMetric
from excel_recorder import MetricExcelRecorder
#ACC
def main(exp_name,net,scale,results_path,pth_path):
check_mkdir(results_path)
to_test = OrderedDict([
('CAMO', camo_path),
('CHAMELEON', chameleon_path),
('COD10K', cod10k_path),
('NC4K', nc4k_path)
])
results = OrderedDict()
img_transform = transforms.Compose([
transforms.Resize((scale,scale)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
to_pil = transforms.ToPILImage()
net.load_state_dict(torch.load(pth_path))
print('Load {} succeed!'.format(exp_name+'.pth'))
net.eval()
path_excel = './results_excel1.xlsx'
with torch.no_grad():
excel_logger = MetricExcelRecorder(xlsx_path=path_excel, dataset_names=[name for name, root in to_test.items()])
start = time.time()
for name, root in to_test.items():
cal_total_seg_metrics = CalTotalMetric()
time_list = []
image_path = os.path.join(root, 'Imgs')
mask_path = os.path.join(root, 'GT')
check_mkdir(os.path.join(results_path, exp_name, name))
img_suffix = 'jpg'
img_list = [os.path.splitext(f)[0] for f in os.listdir(image_path) if f.endswith(img_suffix)]
for idx, img_name in enumerate(img_list):
img = Image.open(os.path.join(image_path, img_name + '.' + img_suffix)).convert('RGB')
mask = np.array(Image.open(os.path.join(mask_path, img_name + '.png')).convert('L'))
w, h = img.size
img_var = Variable(img_transform(img).unsqueeze(0)).cuda()
start_each = time.time()
predictions = net(img_var)
prediction = predictions[-1]
prediction = torch.sigmoid(prediction)
time_each = time.time() - start_each
time_list.append(time_each)
prediction = np.array(transforms.Resize((h, w))(to_pil(prediction.data.squeeze(0).cpu())))
Image.fromarray(prediction).convert('L').save(
os.path.join(results_path, exp_name, name, img_name + '.png'))
cal_total_seg_metrics.step(prediction, mask, mask_path)
print(('{}'.format(exp_name)))
print("{}'s average Time Is : {:.3f} s".format(name, mean(time_list)))
print("{}'s average Time Is : {:.1f} fps".format(name, 1 / mean(time_list)))
results = cal_total_seg_metrics.get_results()
excel_logger(row_data=results, dataset_name=name, method_name=exp_name)
print(results)
end = time.time()
print("Total Testing Time: {}".format(str(datetime.timedelta(seconds=int(end - start)))))
def evluation_with_resultspath(results_path,path_excel):
print(results_path)
_, exp_name = os.path.split(results_path)
to_test = OrderedDict([
('CAMO', camo_path),
('CHAMELEON', chameleon_path),
('COD10K', cod10k_path),
('NC4K', nc4k_path)
])
excel_logger = MetricExcelRecorder(xlsx_path=path_excel, dataset_names=[name for name, root in to_test.items()])
for name, root in to_test.items():
print(os.path.join(results_path,name))
if not os.path.exists(os.path.join(results_path,name)):
continue
print(name)
cal_total_seg_metrics = CalTotalMetric()
image_path = os.path.join(root, 'Imgs')
mask_path = os.path.join(root, 'GT')
img_list = [os.path.splitext(f)[0] for f in os.listdir(image_path) if f.endswith('jpg')]
for idx, img_name in enumerate(img_list):
result_img_path = os.path.join(results_path, name, img_name + '.png')
# if not os.path.exists(result_img_path):
# os.rename(os.path.join(results_path, name, img_name + '.tif'), result_img_path)
prediction = Image.open(result_img_path).convert('L')
mask = Image.open(os.path.join(mask_path, img_name + '.png')).convert('L')
if not prediction.size == mask.size:
mask = mask.resize(prediction.size)
cal_total_seg_metrics.step(np.array(prediction), np.array(mask), mask_path)
results = cal_total_seg_metrics.get_results()
print(results)
excel_logger(row_data=results, dataset_name=name, method_name=exp_name)
def evaluation_COD(exp_name,net,scale,results_path,pth_path):
main(exp_name,net,scale,results_path,pth_path)
if __name__ == '__main__':
os.environ['CUDA_VISIBLE_DEVICES'] = '6'
exp_name = 'SARNet'
from SARNet import SARNet
net = SARNet('pvt_v2_b3').cuda()
pth_path = os.path.join(root,'SARNet/pth/SARNet.pth')
results_path = os.path.join(root,'SARNet/results')
#evluation_with_resultspath(results_path,'./results_1.xlsx')
main(exp_name, net, 384, results_path, pth_path)