File size: 5,138 Bytes
44706c2 | 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 | import os
import matplotlib.ticker as ticker
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image
from scipy import ndimage
class HeatMap:
def __init__(self, image, heat_map, gaussian_std=10):
if isinstance(image, np.ndarray):
height = image.shape[0]
width = image.shape[1]
self.image = image
else:
image = Image.open(image)
width, height = image.size
self.image = image
heatmap_array = (np.asarray(heat_map) * 255.0).astype(np.float32)
heatmap_image = Image.fromarray(heatmap_array)
heatmap_image_resized = heatmap_image.resize((width, height))
heatmap_image_resized = ndimage.gaussian_filter(
np.asarray(heatmap_image_resized),
sigma=(gaussian_std, gaussian_std),
order=0,
)
self.heat_map = np.asarray(heatmap_image_resized)
def plot(
self,
transparency=0.7,
color_map="bwr",
show_axis=False,
show_original=False,
show_colorbar=False,
width_pad=0,
):
if show_original:
plt.subplot(1, 2, 1)
if not show_axis:
plt.axis("off")
plt.imshow(self.image)
x, y = 2, 2
else:
x, y = 1, 1
plt.subplot(1, x, y)
if not show_axis:
plt.axis("off")
plt.imshow(self.image)
plt.imshow(self.heat_map, alpha=transparency, cmap=color_map)
if show_colorbar:
plt.colorbar()
plt.tight_layout(w_pad=width_pad)
plt.show()
def save(
self,
filename,
format="png",
save_path=os.getcwd(),
transparency=0.7,
color_map="bwr",
width_pad=-10,
show_axis=False,
show_original=False,
show_colorbar=False,
**kwargs,
):
if show_original:
plt.subplot(1, 2, 1)
if not show_axis:
plt.axis("off")
plt.imshow(self.image)
x, y = 2, 2
else:
x, y = 1, 1
plt.subplot(1, x, y)
if not show_axis:
plt.axis("off")
plt.imshow(self.image)
plt.imshow(self.heat_map, alpha=transparency, cmap=color_map)
if show_colorbar:
plt.colorbar()
plt.tight_layout(w_pad=width_pad)
plt.savefig(
os.path.join(save_path, filename + "." + format),
format=format,
bbox_inches="tight",
pad_inches=0,
**kwargs,
)
print(f"{filename}.{format} has been successfully saved to {save_path}")
def configure_saliency_plot_style(use_latex=False):
import seaborn as sns
sns.set(style="whitegrid", palette="pastel", font_scale=1.2)
if use_latex:
plt.rc("text", usetex=True)
plt.rc("font", family="serif")
def prepare_observation_image(observation):
image = np.asarray(observation).squeeze()
if image.ndim == 3 and image.shape[-1] == 1:
return image[..., 0]
if image.ndim == 3 and image.shape[-1] not in (3, 4):
return image.mean(axis=-1)
return image
def format_time_label(index, length, use_latex=False):
offset = length - 1 - index
if use_latex:
return r"$o_{t}$" if offset == 0 else rf"$o_{{t-{offset}}}$"
return "o_t" if offset == 0 else f"o_t-{offset}"
def plot_saliency_overlay_row(
saliency_maps,
observations,
output_path,
*,
alpha=0.5,
gaussian_std=6,
cmap="seismic",
use_latex=False,
):
configure_saliency_plot_style(use_latex=use_latex)
length = len(saliency_maps)
vmin = float(np.min(saliency_maps))
vmax = float(np.max(saliency_maps))
fig, axes = plt.subplots(1, length, figsize=(4 * length, 4))
if length == 1:
axes = [axes]
image_artist = None
for index, axis in enumerate(axes):
observation_image = prepare_observation_image(observations[index])
heat_map = HeatMap(
image=observation_image,
heat_map=np.asarray(saliency_maps[index]),
gaussian_std=gaussian_std,
)
if np.asarray(heat_map.image).ndim == 2:
axis.imshow(heat_map.image, cmap="gray")
else:
axis.imshow(heat_map.image)
image_artist = axis.imshow(
heat_map.heat_map,
alpha=alpha,
cmap=cmap,
vmin=vmin,
vmax=vmax,
)
axis.set_title(format_time_label(index, length, use_latex=use_latex), fontsize=24, pad=16)
axis.axis("off")
colorbar_axis = fig.add_axes([0.92, 0.18, 0.015, 0.64])
colorbar = fig.colorbar(image_artist, cax=colorbar_axis, orientation="vertical")
colorbar.ax.tick_params(labelsize=14)
colorbar.ax.yaxis.set_major_formatter(ticker.FormatStrFormatter(r"$\mathdefault{%.1e}$"))
colorbar.update_ticks()
plt.subplots_adjust(left=0.03, right=0.9, bottom=0.08, top=0.88, wspace=0.05)
plt.savefig(output_path, format="pdf", dpi=300, bbox_inches="tight")
plt.show()
|