-
Notifications
You must be signed in to change notification settings - Fork 1
/
cal_iqa_nr.py
159 lines (125 loc) · 4.23 KB
/
cal_iqa_nr.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
# evaluate the restored images with IQA
# PSNR, SSIM, LPIPS are given as example, you can add more IQA in this file
import cv2
import argparse, os, sys, glob
import logging
from datetime import datetime
import os
os.chdir(os.path.dirname(__file__))
import pyiqa
from torch.utils import data as data
import glob
import numpy as np
import math
import random
import torch
def get_timestamp():
return datetime.now().strftime('%y%m%d-%H%M%S')
def setup_logger(logger_name, root, phase, level=logging.INFO, screen=False, tofile=False):
'''set up logger'''
lg = logging.getLogger(logger_name)
formatter = logging.Formatter('%(asctime)s.%(msecs)03d - %(levelname)s: %(message)s',
datefmt='%y-%m-%d %H:%M:%S')
lg.setLevel(level)
if tofile:
log_file = os.path.join(root, phase + '_{}.log'.format(get_timestamp()))
fh = logging.FileHandler(log_file, mode='w')
fh.setFormatter(formatter)
lg.addHandler(fh)
if screen:
sh = logging.StreamHandler()
sh.setFormatter(formatter)
lg.addHandler(sh)
def dict2str(opt, indent_l=1):
'''dict to string for logger'''
msg = ''
for k in opt:
if isinstance(v, dict):
msg += ' ' * (indent_l * 2) + k + ':[\n'
msg += dict2str(v, indent_l + 1)
msg += ' ' * (indent_l * 2) + ']\n'
else:
msg += ' ' * (indent_l * 2) + k + ': ' + str(v) + '\n'
return msg
def img2tensor(imgs, bgr2rgb=True, float32=True):
"""from BasicSR
Numpy array to tensor.
Args:
imgs (list[ndarray] | ndarray): Input images.
bgr2rgb (bool): Whether to change bgr to rgb.
float32 (bool): Whether to change to float32.
Returns:
list[tensor] | tensor: Tensor images. If returned results only have
one element, just return tensor.
"""
def _totensor(img, bgr2rgb, float32):
if img.shape[2] == 3 and bgr2rgb:
if img.dtype == 'float64':
img = img.astype('float32')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
img = torch.from_numpy(img.transpose(2, 0, 1))
if float32:
img = img.float()
return img
if isinstance(imgs, list):
return [_totensor(img, bgr2rgb, float32) for img in imgs]
else:
return _totensor(imgs, bgr2rgb, float32)
def main():
parser = argparse.ArgumentParser()
parser.add_argument(
"--img_path",
nargs="+",
help="path to the input image",
default='/home/tiger/gh/dataset/results/Real_Deg/SUPIR/realPhoto',
)
parser.add_argument(
"--log",
type=str,
nargs="?",
help="path to the log",
default='./iqa_results')
parser.add_argument(
"--log-name",
type=str,
nargs="?",
help="name of your log",
default='test',
)
parser.add_argument(
"--num_img",
type=int,
nargs="?",
help="the number of images evaluated in the folder; 0: all the images are evaludated.",
default=0,
)
opt = parser.parse_args()
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
os.makedirs(opt.log, exist_ok=True)
# init logger
setup_logger('base', opt.log, 'test_' + opt.log_name, level=logging.INFO,
screen=True, tofile=True)
logger = logging.getLogger('base')
logger.info(opt)
# init metrics: you can add more metrics here
iqa_niqe = pyiqa.create_metric('niqe', device=device)
iqa_musiq = pyiqa.create_metric('musiq-koniq',device=device)
iqa_clipiqa = pyiqa.create_metric('clipiqa',device=device)
# record metrics
metrics = { 'niqe': [], 'musiq': [], 'clipiqa': []}
for img_name in sorted(os.listdir(opt.img_path)):
input_sr_path = os.path.join(opt.img_path,img_name)
input_sr_img = cv2.imread(input_sr_path, cv2.IMREAD_COLOR)
sr = img2tensor(input_sr_img, bgr2rgb=True, float32=True).unsqueeze(0).cuda().contiguous()
# PSNR: convert the ycbcr to calculate
sr = sr[..., 4:-4, 4:-4] / 255.
niqe_now = iqa_niqe(sr).item()
metrics['niqe'].append(niqe_now)
musiq_now = iqa_musiq(sr).item()
metrics['musiq'].append(musiq_now)
clipiqa_now = iqa_clipiqa(sr).item()
metrics['clipiqa'].append(clipiqa_now)
for key,value in metrics.items():
logger.info('{}:{:.6f}'.format(key,sum(value)/len(value)))
if __name__ == '__main__':
main()