| 255 | |
| 256 | |
| 257 | class VisImage: |
| 258 | def __init__(self, img, scale=1.0): |
| 259 | """ |
| 260 | Args: |
| 261 | img (ndarray): an RGB image of shape (H, W, 3) in range [0, 255]. |
| 262 | scale (float): scale the input image |
| 263 | """ |
| 264 | self.img = img |
| 265 | self.scale = scale |
| 266 | self.width, self.height = img.shape[1], img.shape[0] |
| 267 | self._setup_figure(img) |
| 268 | |
| 269 | def _setup_figure(self, img): |
| 270 | """ |
| 271 | Args: |
| 272 | Same as in :meth:`__init__()`. |
| 273 | |
| 274 | Returns: |
| 275 | fig (matplotlib.pyplot.figure): top level container for all the image plot elements. |
| 276 | ax (matplotlib.pyplot.Axes): contains figure elements and sets the coordinate system. |
| 277 | """ |
| 278 | fig = mplfigure.Figure(frameon=False) |
| 279 | self.dpi = fig.get_dpi() |
| 280 | # add a small 1e-2 to avoid precision lost due to matplotlib's truncation |
| 281 | # (https://github.com/matplotlib/matplotlib/issues/15363) |
| 282 | fig.set_size_inches( |
| 283 | (self.width * self.scale + 1e-2) / self.dpi, |
| 284 | (self.height * self.scale + 1e-2) / self.dpi, |
| 285 | ) |
| 286 | self.canvas = FigureCanvasAgg(fig) |
| 287 | # self.canvas = mpl.backends.backend_cairo.FigureCanvasCairo(fig) |
| 288 | ax = fig.add_axes([0.0, 0.0, 1.0, 1.0]) |
| 289 | ax.axis("off") |
| 290 | self.fig = fig |
| 291 | self.ax = ax |
| 292 | self.reset_image(img) |
| 293 | |
| 294 | def reset_image(self, img): |
| 295 | """ |
| 296 | Args: |
| 297 | img: same as in __init__ |
| 298 | """ |
| 299 | img = img.astype("uint8") |
| 300 | self.ax.imshow(img, extent=(0, self.width, self.height, 0), interpolation="nearest") |
| 301 | |
| 302 | def save(self, filepath): |
| 303 | """ |
| 304 | Args: |
| 305 | filepath (str): a string that contains the absolute path, including the file name, where |
| 306 | the visualized image will be saved. |
| 307 | """ |
| 308 | self.fig.savefig(filepath) |
| 309 | |
| 310 | def get_image(self): |
| 311 | """ |
| 312 | Returns: |
| 313 | ndarray: |
| 314 | the visualized image of shape (H, W, 3) (RGB) in uint8 type. |