-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathevaluation.py
167 lines (137 loc) · 5.7 KB
/
evaluation.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
import json
import os
import pickle
import torchvision.transforms as transforms
import PIL
import multiprocessing
import pyiqa
from PIL import Image
import torch
from pathlib import Path
import time
from tqdm import tqdm
def worker(
queue: multiprocessing.JoinableQueue,
count: multiprocessing.Value,
) -> None:
while True:
scene_dir = queue.get()
if scene_dir == 'Done':
break
get_images(scene_dir)
with count.get_lock():
count.value += 1
queue.task_done()
def get_images(scene_dir):
print(dataset_root, scene_dir)
cameras_extrinsic_file = os.path.join(dataset_root, "mvimgnet_testset_500", scene_dir, "cam_extrinsics.pkl")
with open(cameras_extrinsic_file, 'rb') as f:
cam_extrinsics = pickle.load(f)
cam_infos = sorted(cam_extrinsics.values(), key=lambda x: x.name)
for cam_info in list(cam_infos):
filename = f"traj_0_{(int(cam_info.name[:-4])-1):03d}.png"
# here, the gt refers to HR_gaussian rendering on traj_0 (since original images in MVImgNet does not cover our novel poses:))
image_path = os.path.join(
dataset_root, "mvimgnet_testset_500", scene_dir, "HR_131072_gaussian", filename
)
image = Image.open(image_path)
# image = transforms.CenterCrop(min(image.size))(image)
gt_image = image.resize(
(256, 256), resample=PIL.Image.BILINEAR
)
name = scene_dir.replace('/', '_') + '_' + cam_info.name[:-4] + '.png'
try:
if os.path.exists(os.path.join(gt_cache_path, name)):
Image.open(os.path.join(gt_cache_path, name))
else:
gt_image.save(os.path.join(gt_cache_path, name))
except:
gt_image.save(os.path.join(gt_cache_path, name))
# load 3D upsampled renderings on traj_0
# filename = f"{(int(cam_info.name[:-4]) - 1):03d}.png"
image_path = os.path.join(
target_root, scene_dir, f"super_gaussian_with_{target}/step_2_fitting_with_3dgs/point_cloud/iteration_2000/predicted", filename
)
image = Image.open(image_path)
try:
if os.path.exists(os.path.join(pred_cache_path, name)):
Image.open(os.path.join(pred_cache_path, name))
else:
image.save(os.path.join(pred_cache_path, name))
except:
image.save(os.path.join(pred_cache_path, name))
# here we load images from original MVImgNet to calculate FID.
image_path = os.path.join(
dataset_root, "mvimgnet_testset_500", scene_dir, "gt_rgb", cam_info.name[:-4] + '.png'
)
image = Image.open(image_path)
image = transforms.CenterCrop(min(image.size))(image)
gt_image = image.resize(
(256, 256), resample=PIL.Image.BILINEAR
)
name = scene_dir.replace('/', '_') + '_' + cam_info.name[:-4] + '.png'
try:
if os.path.exists(os.path.join(fid_gt_cache_path, name)):
Image.open(os.path.join(fid_gt_cache_path, name))
else:
gt_image.save(os.path.join(fid_gt_cache_path, name))
except:
gt_image.save(os.path.join(fid_gt_cache_path, name))
if __name__ == '__main__':
target = 'realbasicvsr' # 'realbasicvsr' or 'gigagan' or 'videogigagan'
num_workers = 16
queue = multiprocessing.JoinableQueue()
count = multiprocessing.Value("i", 0)
dataset_root = 'data'
target_root = f'{target}_test_results'
fid_gt_cache_path = f'evaluations/{target}_prior/gt_fid'
gt_cache_path = f'evaluations/{target}_prior/gt'
pred_cache_path = f'evaluations/{target}_prior/pred'
os.makedirs(gt_cache_path,exist_ok=True)
os.makedirs(pred_cache_path,exist_ok=True)
os.makedirs(fid_gt_cache_path,exist_ok=True)
with open(f'{dataset_root}/mv_imagenet_category.txt', 'r') as f:
category_mapping = {}
for line in f.readlines():
idx, category = line.strip().split(',')
category_mapping[category.strip()] = int(idx.strip())
split_scene_dirs = []
categories = [str(elem) for elem in list(sorted(category_mapping.values()))]
with open(f'{dataset_root}/supergaussian_testset.json', 'r') as f:
split_scene_dirs = json.load(f)
for worker_i in range(num_workers):
process = multiprocessing.Process(
target=worker, args=(queue, count,)
)
process.daemon = True
process.start()
for scene_dir in tqdm(split_scene_dirs):
queue.put((scene_dir))
while True:
time.sleep(5)
print(f"Finished {count.value}/{len(split_scene_dirs)}")
if count.value == len(split_scene_dirs):
break
# Wait for all tasks to be completed
queue.join()
count.value = 0
# Add sentinels to the queue to stop the worker processes
for i in range(num_workers):
queue.put('Done')
fid_metric = pyiqa.create_metric('lpips')
scores = []
for fn in tqdm(Path(gt_cache_path).glob('*.png'), total=len(list(Path(gt_cache_path).glob('*.png')))):
score = fid_metric(str(fn), str(fn).replace('gt', 'pred'))
scores.append(score)
print(f'{target} LPIPS: {torch.stack(scores).mean()}')
fid_metric = pyiqa.create_metric('niqe')
scores = []
for fn in tqdm(Path(pred_cache_path).glob('*.png'), total=len(list(Path(pred_cache_path).glob('*.png')))):
score = fid_metric(str(fn))
scores.append(score)
print(f'{target} NIQE: {torch.stack(scores).mean()}')
img_list = list(sorted(Path(pred_cache_path).glob('*.png')))
import random
random.seed(0)
fid_metric = pyiqa.create_metric('fid')
print("FID: ", fid_metric(fid_gt_cache_path, pred_cache_path))