-
Notifications
You must be signed in to change notification settings - Fork 19
/
lpips_2dirs.py
49 lines (40 loc) · 1.48 KB
/
lpips_2dirs.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
import argparse
import os
import lpips
import torch
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-d0','--dir0', type=str, default='./imgs/ex_dir0')
parser.add_argument('-d1','--dir1', type=str, default='./imgs/ex_dir1')
parser.add_argument('-o','--out', type=str, default='./imgs/example_dists.txt')
parser.add_argument('-v','--version', type=str, default='0.1')
parser.add_argument('--use_gpu', action='store_true', help='turn on flag to use GPU')
opt = parser.parse_args()
## Initializing the model
loss_fn = lpips.LPIPS(net='alex',version=opt.version)
if(opt.use_gpu):
loss_fn.cuda()
# crawl directories
f = open(opt.out,'w')
files = os.listdir(opt.dir0)
diversity_score = []
for file in files:
if(os.path.exists(os.path.join(opt.dir1,file))):
# Load images
img0 = lpips.im2tensor(lpips.load_image(os.path.join(opt.dir0,file))) # RGB image from [-1,1]
img1 = lpips.im2tensor(lpips.load_image(os.path.join(opt.dir1,file)))
if(opt.use_gpu):
img0 = img0.cuda()
img1 = img1.cuda()
# Compute distance
dist01 = loss_fn.forward(img0,img1)
print('%s: %.3f'%(file,dist01))
f.writelines('%s: %.6f\n'%(file,dist01))
diversity_score.append(dist01.detach().cpu())
f.close()
print('============ DS cal over ==============')
# result = torch.cat(diversity_score, dim=0)
result = torch.tensor(diversity_score)
print(result)
mean = result.mean().item()
std = result.std().item()
print('---DiversityScore---{}±{}'.format(mean, std))