forked from MEPP-team/Graphics-LPIPS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGraphicsLpips_csvFile.py
More file actions
127 lines (103 loc) · 4.54 KB
/
Copy pathGraphicsLpips_csvFile.py
File metadata and controls
127 lines (103 loc) · 4.54 KB
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
import argparse
import os
import lpips
import torch
import numpy as np
import statsmodels.api as sm
from scipy import stats
import csv
from itertools import groupby
from operator import itemgetter
from statistics import mean
from decimal import Decimal
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-f','--csvfile', type=str, default='./dataset/TexturedDB_20%_TestList_withnbPatchesPerVP_threth0.6.csv')
parser.add_argument('-m','--modelpath', type=str, default='./checkpoints/GraphicsLPIPS_test1/latest_net_.pth', help='location of model')
parser.add_argument('-o','--out', type=str, default='./GLP_test1_TestsetScores.csv')
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', default=True)
opt = parser.parse_args()
root_refPatches = './dataset\\References_patches_withVP_threth0.6'
root_distPatches = './dataset\\PlaylistsStimuli_patches_withVP_threth0.6'
## Initializing the model
loss_fn = lpips.LPIPS(net='alex',version=opt.version, model_path = opt.modelpath)# e.g. model_path = './checkpoints/Trial1/latest_net_.pth'
if(opt.use_gpu):
loss_fn.cuda()
## Output file
f = open(opt.out,'w')
f.writelines('p0,lpips_alex,MOS\n')
## read Input csv file
List_MOS = []
List_GraphicsLPIPS= []
with open(opt.csvfile) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 0:
print(f'Column names are {", ".join(row)}')
line_count += 1
else:
dist = row[1]
model = row[0]
MOS = row[2]
nbPatches = int(row[3])# for VP1
res = []
resString =''
for p in range(1, nbPatches +1):
refpatch = model + '_Ref_P' + str(p) + '.png'
refpath = os.path.join(root_refPatches, refpatch)
stimuluspatch = dist + '_P' + str(p) + '.png'
stimuluspath = os.path.join(root_distPatches, stimuluspatch)
img0 = lpips.im2tensor(lpips.load_image(refpath)) # RGB image from [-1,1]
img1 = lpips.im2tensor(lpips.load_image(stimuluspath))
if(opt.use_gpu):
img0 = img0.cuda()
img1 = img1.cuda()
dist01 = loss_fn.forward(img0,img1).reshape(1,).item()
if dist01 > 1:
dist01 = 1
res.append(dist01)
Graphicslpips = sum(res)/len(res)
List_GraphicsLPIPS.append(Graphicslpips)
List_MOS.append(float(MOS))
f.writelines('%s, %.6f, %s\n'%(dist,Graphicslpips,MOS))
f.close()
List_GraphicsLPIPS = np.array(List_GraphicsLPIPS)
List_MOS = np.array(List_MOS)
# Instantiate a binomial family model with the logit link function (the default link function).
List_GraphicsLPIPS = sm.add_constant(List_GraphicsLPIPS)
print('List_GraphicsLPIPS:', List_GraphicsLPIPS)
glm_binom = sm.GLM(List_MOS, List_GraphicsLPIPS, family = sm.families.Binomial())#, link = sm.families.links.Logit()
res_regModel = glm_binom.fit()
fitted_GraphicsLpips = res_regModel.predict()
corrPears = stats.pearsonr(fitted_GraphicsLpips, List_MOS)[0]
corrSpear = stats.spearmanr(fitted_GraphicsLpips, List_MOS)[0]
print('pearson %.3f'%corrPears)
print('spearman %.3f'%corrSpear)
import matplotlib.pyplot as plt
# Tri des points pour un tracé fluide de la courbe de régression
sorted_indices = np.argsort(List_GraphicsLPIPS[:,1])
x_sorted = List_GraphicsLPIPS[sorted_indices,1]
y_sorted = fitted_GraphicsLpips[sorted_indices]
# Affichage et sauvegarde du graphique de régression
plt.figure(figsize=(8,6))
plt.scatter(List_GraphicsLPIPS[:,1], List_MOS, label='Données', alpha=0.7, color='blue')
plt.plot(x_sorted, y_sorted, label='Régression logistique', color='red', linewidth=2)
plt.xlabel('Graphics LPIPS')
plt.ylabel('MOS')
plt.title(f'Régression logistique\nPearson={corrPears:.3f} | Spearman={corrSpear:.3f}')
plt.legend()
plt.grid(True)
plt.tight_layout()
plt.savefig('regression_plot.png')
plt.show()
# Sauvegarde des résultats dans un fichier CSV
with open('correlation_summary.csv', 'w', newline='') as summary_file:
writer = csv.writer(summary_file)
writer.writerow(['Pearson', 'Spearman', 'Slope', 'Intercept'])
writer.writerow([
round(corrPears, 4),
round(corrSpear, 4),
round(res_regModel.params[1], 4),
round(res_regModel.params[0], 4)
])