-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheval_util.py
457 lines (378 loc) · 16.7 KB
/
eval_util.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
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
from PIL import Image
import numpy as np
import os
import torch
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
from torchmetrics.multimodal.clip_score import CLIPScore
from statistics import mean
def resized_image_as_array(image_path, new_size=(512, 512)):
image = Image.open(image_path)
if image.size != (512, 512):
image = image.resize((512,512), Image.Resampling.LANCZOS)
image = np.array(image)
return image
def mse(image1_path, image2_path, mask=None):
image1 = resized_image_as_array(image1_path)
image2 = resized_image_as_array(image2_path)
# Mask the edited area if necessary
if mask is not None:
image1[mask] = 0
image2[mask] = 0
# Calculate the squared difference in the unmasked area
squared_diff = np.square(image1 - image2)
# Calculate the mean of the squared differences
mse_value = np.mean(squared_diff)
return mse_value
def LPIPS(image1_path, image2_path, mask=None):
# make sure both images has shape (512, 512, 3)
image1 = resized_image_as_array(image1_path)
image2 = resized_image_as_array(image2_path)
# LPIPS needs the images to be in the [-1, 1] range.
image1 = image1 / 255.0 * 2 - 1
image2 = image2 / 255.0 * 2 - 1
# Mask the edited area if necessary
if mask is not None:
image1[mask] = 0
image2[mask] = 0
# tensors with shape [N, 3, H, W], current [H, W, 3]
image1 = np.transpose(image1, (2, 0, 1))
image2 = np.transpose(image2, (2, 0, 1))
image1 = np.expand_dims(image1, axis=0)
image2 = np.expand_dims(image2, axis=0)
# need to turn np array into tensor
image1 = torch.from_numpy(image1).float()
image2 = torch.from_numpy(image2).float()
lpips = LearnedPerceptualImagePatchSimilarity(net_type='alex')
return lpips(image1, image2).item()
def CLIP(image1_path, prompt, mask=None):
# make sure both images has shape (512, 512, 3)
image1 = resized_image_as_array(image1_path)
# Mask the edited area if necessary
assert mask is None, "CLIP does not involve masking"
# tensors with shape [N, 3, H, W], current [H, W, 3]
image1 = np.transpose(image1, (2, 0, 1))
image1 = np.expand_dims(image1, axis=0)
# need to turn np array into tensor
image1 = torch.from_numpy(image1).float()
clip = CLIPScore(model_name_or_path="openai/clip-vit-base-patch16")
score = clip(image1, prompt)
score.detach()
return score.item()
def resize_and_combine_masks(mask_lists, new_size=(512, 512)):
combined_masks = []
for mask_list in mask_lists:
# Store the resized masks to combine later if necessary
resized_masks = []
for mask_path in mask_list:
# Read and resize the mask
mask = Image.open(mask_path)
mask = mask.convert('L')
mask = mask.resize(new_size)
# Convert mask to binary array (0 and 1)
mask_array = np.array(mask)
# print("sum of pixels:", np.sum(mask_array > 230))
mask_array = (mask_array > 127).astype(int) # Assuming the mask is grayscale
# Append to list of resized masks
resized_masks.append(mask_array)
# Combine masks by taking the element-wise maximum if there's more than one
if len(resized_masks) > 1:
combined_mask = np.maximum.reduce(resized_masks)
else:
combined_mask = resized_masks[0]
combined_masks.append(combined_mask)
return combined_masks
# func takes in two image paths, one mask (optional) and
# returns a list of [file_name, eval_result]
def get_evals(func, path_list1, path_list2, mask_list=None):
result = []
if mask_list is None:
for image1, image2 in zip(path_list1, path_list2):
eval_result = func(image1, image2)
file_name = image1.split('.')[-2].split('/')[-1]
# print(f"MSE of {file_name}: {round(eval_result, 2)}")
res = [file_name, eval_result]
result.append(res)
else:
for image1, image2, mask in zip(path_list1, path_list2, mask_list):
eval_result = func(image1, image2, mask)
file_name = image1.split('.')[-2].split('/')[-1]
# print(f"MSE of {file_name}: {round(eval_result, 2)}")
res = [file_name, eval_result]
result.append(res)
return result
def print_result(ours, baseline):
col_widths = [15, 10, 10, 10]
print(f'{"Label":<{col_widths[0]}} {"Ours":<{col_widths[1]}} {"Baseline":<{col_widths[2]}} {"Diff":<{col_widths[3]}}')
statistics = {"labels":[], "ours":[], "baseline":[], "diff":[]}
for line in zip(ours, baseline):
assert line[0][0] == line[1][0]
label = line[0][0]
ours_value = line[0][1]
baseline_value = line[1][1]
statistics["labels"].append(label)
statistics["ours"].append(ours_value)
statistics["baseline"].append(baseline_value)
statistics["diff"].append(ours_value-baseline_value)
print(f'{label:<{col_widths[0]}} {ours_value:<{col_widths[1]}.2f} {baseline_value:<{col_widths[2]}.2f} {ours_value-baseline_value:<{col_widths[3]}.2f}')
# print average of ours and baseline
ours_mean = mean([x[1] for x in ours])
baseline_mean = mean([x[1] for x in baseline])
print(f"\nAverage:")
print(f'{"ours:":<{15}} {ours_mean:<{20}.2f}')
print(f'{"baseline:":<{15}} {baseline_mean:<{20}.2f}')
print(f'{"diff:":<{15}} {ours_mean-baseline_mean:<{20}.2f}')
statistics["ours_mean"] = ours_mean
statistics["baseline_mean"] = baseline_mean
statistics["diff_mean"] = ours_mean-baseline_mean
return statistics
def write_to_csv(statistics, file_name="lpips"):
import csv
with open(os.path.join(output_path, f'{file_name}.csv'), 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["Label", "Ours", "Baseline", "Diff"])
for line in zip(statistics["labels"], statistics["ours"], statistics["baseline"], statistics["diff"]):
label = line[0]
ours_value = line[1]
baseline_value = line[2]
diff_value = line[3]
writer.writerow([label, ours_value, baseline_value, diff_value])
writer.writerow(["Average", statistics["ours_mean"], statistics["baseline_mean"], statistics["diff_mean"]])
def print_result_list(ours, baselines):
num_baselines = len(baselines)
col_widths = [15] + [10] * (num_baselines + 1)
# Header
headers = ["Label", "Ours"] + [f"Baseline{i+1}" for i in range(num_baselines)]
print(" ".join([h.ljust(col_widths[i]) for i, h in enumerate(headers)]))
# Statistics
statistics = {"labels": [], "ours": []}
for i in range(num_baselines):
statistics[f"baseline{i+1}"] = []
for line in zip(ours, *baselines):
label = line[0][0]
ours_value = line[0][1]
statistics["labels"].append(label)
statistics["ours"].append(ours_value)
values = [label, ours_value]
for i, baseline in enumerate(line[1:]):
# assert label == baseline[0] # not work for talktoedit due to missing image
baseline_value = baseline[1]
statistics[f"baseline{i+1}"].append(baseline_value)
values.append(baseline_value)
print(" ".join([f"{v:<{col_widths[i]}.4f}" if isinstance(v, float) else f"{v:<{col_widths[i]}}" for i, v in enumerate(values)]))
# Average calculation
ours_mean = mean([x[1] for x in ours])
statistics["ours_mean"] = ours_mean
print(f"\nAverage:")
print(f'{"ours:":<{15}} {ours_mean:<{20}.4f}')
for i in range(num_baselines):
baseline_mean = mean([x[1] for x in baselines[i]])
statistics[f"baseline{i+1}_mean"] = baseline_mean
print(f'{"baseline" + str(i+1) + ":":<{15}} {baseline_mean:<{20}.4f}')
return statistics
def write_to_csv_list(statistics, file_name="lpips_all"):
import csv
import os
# Determine the number of baselines
num_baselines = len([key for key in statistics if key.startswith("baseline") and "_mean" not in key])
# Prepare headers
headers = ["Label", "Ours"] + [f"Baseline{i+1}" for i in range(num_baselines)]
averages = ["Average", statistics["ours_mean"]] + [statistics[f"baseline{i+1}_mean"] for i in range(num_baselines)]
with open(os.path.join(output_path, f'{file_name}.csv'), 'w', newline='') as file:
writer = csv.writer(file)
# Write headers
writer.writerow(headers)
# Write data rows
for i, label in enumerate(statistics["labels"]):
row = [label, statistics["ours"][i]] + [statistics[f"baseline{j+1}"][i] for j in range(num_baselines)]
writer.writerow(row)
# Write averages
writer.writerow(averages)
if __name__ == "__main__":
# hardcode the filenames for now
output_path = "assets/eval_results"
images_path = "assets/eval_images"
file_names = [
"0_no_smile.png",
"13_smiling.png",
"17_no_bangs.png",
"stefano_bangs.png",
"stefano_glasses.png",
"stefano_shaven.png",
"stefano_young.png"
]
file_names_jpg = [
"0_no_smile.jpg",
"13_smiling.jpg",
"17_no_bangs.jpg",
"stefano_bangs.jpg",
"stefano_glasses.jpg",
"stefano_shaven.jpg",
"stefano_young.jpg"
]
file_names_talk = [
"0_no_smile.png",
"13_smiling.png",
"17_no_bangs.png",
"stefano_bangs.png",
"stefano.jpg",
"stefano_shaven.png",
"stefano_young.png"
]
ours = [os.path.join(images_path, "ours", f) for f in file_names]
p2p = [os.path.join(images_path, "pix2pix-baseline", f) for f in file_names]
sc_fegan = [os.path.join(images_path, "SC-FEGAN", f) for f in file_names_jpg]
talk_to_edit = [os.path.join(images_path, "TalkToEdit", f) for f in file_names_talk]
# rec files in png
rec_file_names = [
"0.png",
"13.png",
"17.png",
"stefano.png",
"stefano.png",
"stefano.png",
"stefano.png"
]
# original files in jpg
original_file_names = [
"0.jpg",
"13.jpg",
"17.jpg",
"stefano.jpg",
"stefano.jpg",
"stefano.jpg",
"stefano.jpg"
]
rec = [os.path.join(images_path, "rec", f) for f in rec_file_names]
original = [os.path.join(images_path, "original", f) for f in original_file_names]
masks_names = [
["00000_mouth.png"],
["00013_l_lip.png", "00013_u_lip.png"],
["00017_hair.png"],
["stefano_bangs_mask.jpg"],
["stefano_glasses_mask.jpg"],
["stefano_beard_mask.jpg"],
["stefano_age_mask.jpg"],
]
masks_list = [[os.path.join(images_path, "masks", file) for file in sublist] for sublist in masks_names]
combined_masks = resize_and_combine_masks(masks_list)
src_descriptions = [
"mouth open wide smiling",
"not smiling",
"white woman with blonde hair bangs",
"white man with black hair without bangs",
"without glasses",
"beard",
"middle aged white man"
]
dst_descriptions = [
"mouth closed not smiling",
"smiling",
"white woman with blonde hair without bangs",
"white man with black hair bangs",
"wearing glasses",
"clean shaven face",
"young adult white man"
]
prompts = [
"a woman wearing a tiara and smiling at the camera",
"a woman with long blonde hair and blue eyes",
"a woman with long blonde hair and blue eyes",
"a close up of a person wearing a shirt and tie",
"a close up of a person wearing a shirt and tie",
"a close up of a person wearing a shirt and tie",
"a close up of a person wearing a shirt and tie"
]
dst_sentences = [x[0]+", "+x[1] for x in zip(prompts, dst_descriptions)]
# # Calculate MSE
# print("----------------------------------------")
# print("Masked MSE")
# print("Ours vs Rec, P2P vs Rec")
# ours_vs_res = get_evals(mse,ours,rec,combined_masks)
# p2p_vs_res = get_evals(mse,p2p,rec,combined_masks)
# ours_vs_p2p_rec_masked = print_result(ours_vs_res, p2p_vs_res)
# print()
# print("Ours vs Original, P2P vs Original")
# ours_vs_orig = get_evals(mse,ours,original,combined_masks)
# p2p_vs_orig = get_evals(mse,p2p,original,combined_masks)
# ours_vs_p2p_orig_masked = print_result(ours_vs_orig, p2p_vs_orig)
# write_to_csv(ours_vs_p2p_orig_masked, "mse_masked")
# print("----------------------------------------")
# print("Unmasked MSE")
# print("Ours vs Rec, P2P vs Rec")
# ours_vs_res = get_evals(mse,ours,rec)
# p2p_vs_res = get_evals(mse,p2p,rec)
# ours_vs_p2p_rec_unmasked = print_result(ours_vs_res, p2p_vs_res)
# print()
# print("Ours vs Original, P2P vs Original")
# ours_vs_orig = get_evals(mse,ours,original)
# p2p_vs_orig = get_evals(mse,p2p,original)
# ours_vs_p2p_orig_unmasked = print_result(ours_vs_orig, p2p_vs_orig)
# write_to_csv(ours_vs_p2p_orig_unmasked, "mse_unmasked")
# # Calculate LPIPS
# print("----------------------------------------")
# print("Masked LPIPS")
# print("Ours vs Rec, P2P vs Rec")
# ours_vs_res = get_evals(LPIPS,ours,rec,combined_masks)
# p2p_vs_res = get_evals(LPIPS,p2p,rec,combined_masks)
# ours_vs_p2p_rec_masked = print_result(ours_vs_res, p2p_vs_res)
# print()
# print("Ours vs Original, P2P vs Original")
# ours_vs_orig = get_evals(LPIPS,ours,original,combined_masks)
# p2p_vs_orig = get_evals(LPIPS,p2p,original,combined_masks)
# ours_vs_p2p_orig_masked = print_result(ours_vs_orig, p2p_vs_orig)
# write_to_csv(ours_vs_p2p_orig_masked, "lpips_masked")
# print("----------------------------------------")
# print("Unmasked LPIPS")
# print("Ours vs Rec, P2P vs Rec")
# ours_vs_res = get_evals(LPIPS,ours,rec)
# p2p_vs_res = get_evals(LPIPS,p2p,rec)
# ours_vs_p2p_rec_unmasked = print_result(ours_vs_res, p2p_vs_res)
# print()
# print("Ours vs Original, P2P vs Original")
# ours_vs_orig = get_evals(LPIPS,ours,original)
# p2p_vs_orig = get_evals(LPIPS,p2p,original)
# ours_vs_p2p_orig_unmasked = print_result(ours_vs_orig, p2p_vs_orig)
# write_to_csv(ours_vs_p2p_orig_unmasked, "lpips_unmasked")
# # Calculate CLIP
# print("----------------------------------------")
# print("CLIP")
# print("Ours vs P2P vs Original")
# ours_clip = get_evals(CLIP,ours,dst_sentences)
# p2p_clip = get_evals(CLIP,p2p,dst_sentences)
# original_clip = get_evals(CLIP,original,dst_sentences)
# # print("ours", ours_clip)
# # print("p2p", p2p_clip)
# # print("original", original_clip)
# ours_vs_p2p_clip = print_result(ours_clip, p2p_clip)
# write_to_csv(ours_vs_p2p_clip, "clip")
# # p2p = get_evals(CLIP,p2p,rec,combined_masks)
# # original = get_evals(CLIP,p2p,rec,combined_masks)
# Calculate LPIPS
print("----------------------------------------")
print("Masked LPIPS")
print("Ours vs Original, P2P vs Original, TalkToEdit vs Original, SC-FEGAN vs Original")
ours_vs_orig = get_evals(LPIPS,ours,original,combined_masks)
p2p_vs_orig = get_evals(LPIPS,p2p,original,combined_masks)
talk_to_edit_vs_orig = get_evals(LPIPS,talk_to_edit,original,combined_masks)
sc_fegan_vs_orig = get_evals(LPIPS,sc_fegan,original,combined_masks)
ours_vs_others_orig_masked = print_result_list(ours_vs_orig, [p2p_vs_orig, talk_to_edit_vs_orig, sc_fegan_vs_orig])
write_to_csv_list(ours_vs_others_orig_masked, "all_lpips_masked")
print()
print("Ours vs Original, P2P vs Original, TalkToEdit vs Original, SC-FEGAN vs Original")
ours_vs_orig = get_evals(LPIPS,ours,original)
p2p_vs_orig = get_evals(LPIPS,p2p,original)
talk_to_edit_vs_orig = get_evals(LPIPS,talk_to_edit,original)
sc_fegan_vs_orig = get_evals(LPIPS,sc_fegan,original)
ours_vs_others_orig_unmasked = print_result_list(ours_vs_orig, [p2p_vs_orig, talk_to_edit_vs_orig, sc_fegan_vs_orig])
write_to_csv_list(ours_vs_others_orig_unmasked, "all_lpips_unmasked")
# Calculate CLIP scores for all methods
print("----------------------------------------")
print("CLIP Scores")
print("Ours vs Original, P2P vs Original, TalkToEdit vs Original, SC-FEGAN vs Original")
ours_clip = get_evals(CLIP, ours, dst_sentences)
p2p_clip = get_evals(CLIP, p2p, dst_sentences)
talk_to_edit_clip = get_evals(CLIP, talk_to_edit, dst_sentences)
sc_fegan_clip = get_evals(CLIP, sc_fegan, dst_sentences)
# Print results and write to CSV for CLIP scores
ours_vs_others_clip = print_result_list(ours_clip, [p2p_clip, talk_to_edit_clip, sc_fegan_clip])
write_to_csv_list(ours_vs_others_clip, "all_clip")