File size: 3,185 Bytes
5f5f544
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.

import math
from pathlib import Path

import cv2
import numpy as np
import torch
from sapiens.registry import VISUALIZERS
from torch import nn


@VISUALIZERS.register_module()
class BaseVisualizer(nn.Module):
    def __init__(
        self,
        output_dir: str,
        vis_interval: int = 100,
        vis_max_samples: int = 16,
        vis_downsample: int = 2,
    ):
        super().__init__()
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(parents=True, exist_ok=True)
        self.vis_max_samples = vis_max_samples
        self.vis_interval = vis_interval
        self.vis_downsample = vis_downsample

    def add_batch(self, data_batch: dict, logs: dict, step: int):
        images = data_batch["data_samples"]["image"].detach().cpu()
        outputs = logs["outputs"].detach().cpu()  # (B, C, H, W)

        if outputs.dtype == torch.bfloat16:
            images = images.float()
            outputs = outputs.float()

        batch_size = min(len(images), self.vis_max_samples)

        save_images = []

        for i in range(batch_size):
            gt_image = images[i].permute(1, 2, 0).cpu().numpy() * 255
            pred_image = outputs[i].permute(1, 2, 0).cpu().numpy() * 255

            gt_image = np.clip(gt_image, 0, 255).astype(np.uint8)
            pred_image = np.clip(pred_image, 0, 255).astype(np.uint8)

            image_height, image_width = gt_image.shape[:2]

            if self.vis_downsample > 1:
                image_height = int(image_height / self.vis_downsample)
                image_width = int(image_width / self.vis_downsample)

                gt_image = cv2.resize(
                    gt_image,
                    (image_width, image_height),
                    interpolation=cv2.INTER_AREA,
                )
                pred_image = cv2.resize(
                    pred_image,
                    (image_width, image_height),
                    interpolation=cv2.INTER_AREA,
                )

            save_image = np.concatenate([gt_image, pred_image], axis=1)
            save_images.append(save_image)

        out_file = self.output_dir / f"{step:06d}.jpg"
        image_height, image_width = save_images[0].shape[:2]
        cols = int(math.ceil(math.sqrt(batch_size)))
        rows = int(math.ceil(batch_size / cols))

        canvas_height = rows * image_height
        canvas_width = cols * image_width

        canvas = np.zeros((canvas_height, canvas_width, 3), dtype=np.uint8)

        for idx, image in enumerate(save_images):
            row = idx // cols
            col = idx % cols
            canvas[
                row * image_height : (row + 1) * image_height,
                col * image_width : (col + 1) * image_width,
            ] = image

        ## downsample canvas by 2x
        canvas = cv2.resize(
            canvas,
            (canvas_width, canvas_height),
            interpolation=cv2.INTER_AREA,
        )
        cv2.imwrite(out_file, canvas)

        return