Spaces:
Runtime error
Runtime error
File size: 15,187 Bytes
2df809d |
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 |
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
from eval.video_depth.tools import depth_evaluation, group_by_directory
import numpy as np
import cv2
from tqdm import tqdm
import glob
from PIL import Image
import argparse
import json
from eval.video_depth.metadata import dataset_metadata
def get_args_parser():
parser = argparse.ArgumentParser()
parser.add_argument(
"--output_dir",
type=str,
default="",
help="value for outdir",
)
parser.add_argument(
"--eval_dataset", type=str, default="nyu", choices=list(dataset_metadata.keys())
)
parser.add_argument(
"--align",
type=str,
default="scale&shift",
choices=["scale&shift", "scale", "metric"],
)
return parser
def main(args):
if args.eval_dataset == "sintel":
TAG_FLOAT = 202021.25
def depth_read(filename):
"""Read depth data from file, return as numpy array."""
f = open(filename, "rb")
check = np.fromfile(f, dtype=np.float32, count=1)[0]
assert (
check == TAG_FLOAT
), " depth_read:: Wrong tag in flow file (should be: {0}, is: {1}). Big-endian machine? ".format(
TAG_FLOAT, check
)
width = np.fromfile(f, dtype=np.int32, count=1)[0]
height = np.fromfile(f, dtype=np.int32, count=1)[0]
size = width * height
assert (
width > 0 and height > 0 and size > 1 and size < 100000000
), " depth_read:: Wrong input size (width = {0}, height = {1}).".format(
width, height
)
depth = np.fromfile(f, dtype=np.float32, count=-1).reshape((height, width))
return depth
pred_pathes = glob.glob(
f"{args.output_dir}/*/frame_*.npy"
) # TODO: update the path to your prediction
pred_pathes = sorted(pred_pathes)
if len(pred_pathes) > 643:
full = True
else:
full = False
if full:
depth_pathes = glob.glob(f"data/sintel/training/depth/*/*.dpt")
depth_pathes = sorted(depth_pathes)
else:
seq_list = [
"alley_2",
"ambush_4",
"ambush_5",
"ambush_6",
"cave_2",
"cave_4",
"market_2",
"market_5",
"market_6",
"shaman_3",
"sleeping_1",
"sleeping_2",
"temple_2",
"temple_3",
]
depth_pathes_folder = [
f"data/sintel/training/depth/{seq}" for seq in seq_list
]
depth_pathes = []
for depth_pathes_folder_i in depth_pathes_folder:
depth_pathes += glob.glob(depth_pathes_folder_i + "/*.dpt")
depth_pathes = sorted(depth_pathes)
def get_video_results():
grouped_pred_depth = group_by_directory(pred_pathes)
grouped_gt_depth = group_by_directory(depth_pathes)
gathered_depth_metrics = []
for key in tqdm(grouped_pred_depth.keys()):
pd_pathes = grouped_pred_depth[key]
gt_pathes = grouped_gt_depth[key.replace("_pred_depth", "")]
gt_depth = np.stack(
[depth_read(gt_path) for gt_path in gt_pathes], axis=0
)
pr_depth = np.stack(
[
cv2.resize(
np.load(pd_path),
(gt_depth.shape[2], gt_depth.shape[1]),
interpolation=cv2.INTER_CUBIC,
)
for pd_path in pd_pathes
],
axis=0,
)
# for depth eval, set align_with_lad2=False to use median alignment; set align_with_lad2=True to use scale&shift alignment
if args.align == "scale&shift":
depth_results, error_map, depth_predict, depth_gt = (
depth_evaluation(
pr_depth,
gt_depth,
max_depth=70,
align_with_lad2=True,
use_gpu=True,
post_clip_max=70,
)
)
elif args.align == "scale":
depth_results, error_map, depth_predict, depth_gt = (
depth_evaluation(
pr_depth,
gt_depth,
max_depth=70,
align_with_scale=True,
use_gpu=True,
post_clip_max=70,
)
)
elif args.align == "metric":
depth_results, error_map, depth_predict, depth_gt = (
depth_evaluation(
pr_depth,
gt_depth,
max_depth=70,
metric_scale=True,
use_gpu=True,
post_clip_max=70,
)
)
gathered_depth_metrics.append(depth_results)
depth_log_path = f"{args.output_dir}/result_{args.align}.json"
average_metrics = {
key: np.average(
[metrics[key] for metrics in gathered_depth_metrics],
weights=[
metrics["valid_pixels"] for metrics in gathered_depth_metrics
],
)
for key in gathered_depth_metrics[0].keys()
if key != "valid_pixels"
}
print("Average depth evaluation metrics:", average_metrics)
with open(depth_log_path, "w") as f:
f.write(json.dumps(average_metrics))
get_video_results()
elif args.eval_dataset == "bonn":
def depth_read(filename):
# loads depth map D from png file
# and returns it as a numpy array
depth_png = np.asarray(Image.open(filename))
# make sure we have a proper 16bit depth map here.. not 8bit!
assert np.max(depth_png) > 255
depth = depth_png.astype(np.float64) / 5000.0
depth[depth_png == 0] = -1.0
return depth
seq_list = ["balloon2", "crowd2", "crowd3", "person_tracking2", "synchronous"]
img_pathes_folder = [
f"data/bonn/rgbd_bonn_dataset/rgbd_bonn_{seq}/rgb_110/*.png"
for seq in seq_list
]
img_pathes = []
for img_pathes_folder_i in img_pathes_folder:
img_pathes += glob.glob(img_pathes_folder_i)
img_pathes = sorted(img_pathes)
depth_pathes_folder = [
f"data/bonn/rgbd_bonn_dataset/rgbd_bonn_{seq}/depth_110/*.png"
for seq in seq_list
]
depth_pathes = []
for depth_pathes_folder_i in depth_pathes_folder:
depth_pathes += glob.glob(depth_pathes_folder_i)
depth_pathes = sorted(depth_pathes)
pred_pathes = glob.glob(
f"{args.output_dir}/*/frame*.npy"
) # TODO: update the path to your prediction
pred_pathes = sorted(pred_pathes)
def get_video_results():
grouped_pred_depth = group_by_directory(pred_pathes)
grouped_gt_depth = group_by_directory(depth_pathes, idx=-2)
gathered_depth_metrics = []
for key in tqdm(grouped_gt_depth.keys()):
pd_pathes = grouped_pred_depth[key[10:]]
gt_pathes = grouped_gt_depth[key]
gt_depth = np.stack(
[depth_read(gt_path) for gt_path in gt_pathes], axis=0
)
pr_depth = np.stack(
[
cv2.resize(
np.load(pd_path),
(gt_depth.shape[2], gt_depth.shape[1]),
interpolation=cv2.INTER_CUBIC,
)
for pd_path in pd_pathes
],
axis=0,
)
# for depth eval, set align_with_lad2=False to use median alignment; set align_with_lad2=True to use scale&shift alignment
if args.align == "scale&shift":
depth_results, error_map, depth_predict, depth_gt = (
depth_evaluation(
pr_depth,
gt_depth,
max_depth=70,
align_with_lad2=True,
use_gpu=True,
)
)
elif args.align == "scale":
depth_results, error_map, depth_predict, depth_gt = (
depth_evaluation(
pr_depth,
gt_depth,
max_depth=70,
align_with_scale=True,
use_gpu=True,
)
)
elif args.align == "metric":
depth_results, error_map, depth_predict, depth_gt = (
depth_evaluation(
pr_depth,
gt_depth,
max_depth=70,
metric_scale=True,
use_gpu=True,
)
)
gathered_depth_metrics.append(depth_results)
# seq_len = gt_depth.shape[0]
# error_map = error_map.reshape(seq_len, -1, error_map.shape[-1]).cpu()
# error_map_colored = colorize(error_map, range=(error_map.min(), error_map.max()), append_cbar=True)
# ImageSequenceClip([x for x in (error_map_colored.numpy()*255).astype(np.uint8)], fps=10).write_videofile(f'{args.output_dir}/errormap_{key}_{args.align}.mp4', fps=10)
depth_log_path = f"{args.output_dir}/result_{args.align}.json"
average_metrics = {
key: np.average(
[metrics[key] for metrics in gathered_depth_metrics],
weights=[
metrics["valid_pixels"] for metrics in gathered_depth_metrics
],
)
for key in gathered_depth_metrics[0].keys()
if key != "valid_pixels"
}
print("Average depth evaluation metrics:", average_metrics)
with open(depth_log_path, "w") as f:
f.write(json.dumps(average_metrics))
get_video_results()
elif args.eval_dataset == "kitti":
def depth_read(filename):
# loads depth map D from png file
# and returns it as a numpy array,
# for details see readme.txt
img_pil = Image.open(filename)
depth_png = np.array(img_pil, dtype=int)
# make sure we have a proper 16bit depth map here.. not 8bit!
assert np.max(depth_png) > 255
depth = depth_png.astype(float) / 256.0
depth[depth_png == 0] = -1.0
return depth
depth_pathes = glob.glob(
"data/kitti/depth_selection/val_selection_cropped/groundtruth_depth_gathered/*/*.png"
)
depth_pathes = sorted(depth_pathes)
pred_pathes = glob.glob(
f"{args.output_dir}/*/frame_*.npy"
) # TODO: update the path to your prediction
pred_pathes = sorted(pred_pathes)
def get_video_results():
grouped_pred_depth = group_by_directory(pred_pathes)
grouped_gt_depth = group_by_directory(depth_pathes)
gathered_depth_metrics = []
for key in tqdm(grouped_pred_depth.keys()):
pd_pathes = grouped_pred_depth[key]
gt_pathes = grouped_gt_depth[key]
gt_depth = np.stack(
[depth_read(gt_path) for gt_path in gt_pathes], axis=0
)
pr_depth = np.stack(
[
cv2.resize(
np.load(pd_path),
(gt_depth.shape[2], gt_depth.shape[1]),
interpolation=cv2.INTER_CUBIC,
)
for pd_path in pd_pathes
],
axis=0,
)
# for depth eval, set align_with_lad2=False to use median alignment; set align_with_lad2=True to use scale&shift alignment
if args.align == "scale&shift":
depth_results, error_map, depth_predict, depth_gt = (
depth_evaluation(
pr_depth,
gt_depth,
max_depth=None,
align_with_lad2=True,
use_gpu=True,
)
)
elif args.align == "scale":
depth_results, error_map, depth_predict, depth_gt = (
depth_evaluation(
pr_depth,
gt_depth,
max_depth=None,
align_with_scale=True,
use_gpu=True,
)
)
elif args.align == "metric":
depth_results, error_map, depth_predict, depth_gt = (
depth_evaluation(
pr_depth,
gt_depth,
max_depth=None,
metric_scale=True,
use_gpu=True,
)
)
gathered_depth_metrics.append(depth_results)
depth_log_path = f"{args.output_dir}/result_{args.align}.json"
average_metrics = {
key: np.average(
[metrics[key] for metrics in gathered_depth_metrics],
weights=[
metrics["valid_pixels"] for metrics in gathered_depth_metrics
],
)
for key in gathered_depth_metrics[0].keys()
if key != "valid_pixels"
}
print("Average depth evaluation metrics:", average_metrics)
with open(depth_log_path, "w") as f:
f.write(json.dumps(average_metrics))
get_video_results()
if __name__ == "__main__":
args = get_args_parser()
args = args.parse_args()
main(args)
|