a b/sybil/utils/visualization.py
1
import numpy as np
2
import torch
3
import torch.nn.functional as F
4
from sybil.serie import Serie
5
from typing import Dict, List, Union
6
import os
7
8
def collate_attentions(attention_dict: Dict[str, np.ndarray], N: int, eps=1e-6) -> np.ndarray:
9
    a1 = attention_dict["image_attention_1"]
10
    v1 = attention_dict["volume_attention_1"]
11
12
    a1 = torch.Tensor(a1)
13
    v1 = torch.Tensor(v1)
14
15
    # take mean attention over ensemble
16
    a1 = torch.exp(a1).mean(0)
17
    v1 = torch.exp(v1).mean(0)
18
19
    attention = a1 * v1.unsqueeze(-1)
20
    attention = attention.view(1, 25, 16, 16)
21
22
    attention_up = F.interpolate(
23
        attention.unsqueeze(0), (N, 512, 512), mode="trilinear"
24
    )
25
    attention_up = attention_up.cpu().numpy()
26
    attention_up = attention_up.squeeze()
27
    if eps:
28
        attention_up[attention_up <= eps] = 0.0
29
30
    return attention_up
31
32
def build_overlayed_images(images: List[np.ndarray], attention: np.ndarray, gain: int = 3):
33
    overlayed_images = []
34
    N = len(images)
35
    for i in range(N):
36
        overlayed = np.zeros((512, 512, 3))
37
        overlayed[..., 2] = images[i]
38
        overlayed[..., 1] = images[i]
39
        overlayed[..., 0] = np.clip(
40
            (attention[i, ...] * gain * 256) + images[i],
41
            a_min=0,
42
            a_max=255,
43
        )
44
45
        overlayed_images.append(np.uint8(overlayed))
46
47
    return overlayed_images
48
49
50
def visualize_attentions(
51
    series: Union[Serie, List[Serie]],
52
    attentions: List[Dict[str, np.ndarray]],
53
    save_directory: str = None,
54
    gain: int = 3,
55
) -> List[List[np.ndarray]]:
56
    """
57
    Args:
58
        series (Serie): series object
59
        attentions (Dict[str, np.ndarray]): attention dictionary output from model
60
        save_directory (str, optional): where to save the images. Defaults to None.
61
        gain (int, optional): how much to scale attention values by for visualization. Defaults to 3.
62
63
    Returns:
64
        List[List[np.ndarray]]: list of list of overlayed images
65
    """
66
67
    if isinstance(series, Serie):
68
        series = [series]
69
70
    series_overlays = []
71
    for serie_idx, serie in enumerate(series):
72
        images = serie.get_raw_images()
73
        N = len(images)
74
        cur_attention = collate_attentions(attentions[serie_idx], N)
75
76
        overlayed_images = build_overlayed_images(images, cur_attention, gain)
77
78
        if save_directory is not None:
79
            save_path = os.path.join(save_directory, f"serie_{serie_idx}")
80
            save_images(overlayed_images, save_path, f"serie_{serie_idx}")
81
82
        series_overlays.append(overlayed_images)
83
    return series_overlays
84
85
86
def save_images(img_list: List[np.ndarray], directory: str, name: str):
87
    """
88
    Saves a list of images as a GIF in the specified directory with the given name.
89
90
    Args:
91
        ``img_list`` (List[np.ndarray]): A list of numpy arrays representing the images to be saved.
92
        ``directory`` (str): The directory where the GIF should be saved.
93
        ``name`` (str): The name of the GIF file.
94
95
    Returns:
96
        None
97
    """
98
    import imageio
99
    os.makedirs(directory, exist_ok=True)
100
    path = os.path.join(directory, f"{name}.gif")
101
    imageio.mimsave(path, img_list)