Save image to file, ensuring there's no whitespace around the edge.
(images, labels, filename, transform_name, transform_args, shapes, colorbar=False)
| 310 | |
| 311 | |
| 312 | def save_image(images, labels, filename, transform_name, transform_args, shapes, colorbar=False): |
| 313 | """Save image to file, ensuring there's no whitespace around the edge.""" |
| 314 | plt.rcParams.update({"font.family": "monospace"}) |
| 315 | plt.style.use("dark_background") |
| 316 | nrow = len(images) # before and after (should always be 2) |
| 317 | ncol = len(images[0]) # num orthogonal views (either 1 or 3) |
| 318 | # roughly estimate the height_ratios of the first:second row |
| 319 | hs = [float(r[0].shape[0]) for r in images] |
| 320 | fig = plt.figure(tight_layout=True) |
| 321 | spec = fig.add_gridspec(nrow, ncol, hspace=0, wspace=0, height_ratios=hs) |
| 322 | for row in range(nrow): |
| 323 | vmin = min(i.min() for i in images[row]) |
| 324 | vmax = max(i.max() for i in images[row]) |
| 325 | for col in range(ncol): |
| 326 | ax = fig.add_subplot(spec[row, col]) |
| 327 | imshow = ax.imshow(images[row][col], cmap="gray", vmin=vmin, vmax=vmax) |
| 328 | ax.set_aspect("equal") |
| 329 | if colorbar and col == ncol - 1: |
| 330 | plt.colorbar(imshow, ax=ax) |
| 331 | if col == 0: |
| 332 | y_label = "After" if row else "Before" |
| 333 | y_label += ("\n" + shapes[row]) if shapes[0] != shapes[1] else "" |
| 334 | ax.set_ylabel(y_label) |
| 335 | # print yticks for the right most column |
| 336 | if col != ncol - 1 or colorbar: |
| 337 | ax.set_yticks([]) |
| 338 | else: |
| 339 | ax.yaxis.tick_right() |
| 340 | for n, label in enumerate(ax.yaxis.get_ticklabels()): |
| 341 | if n > 2: |
| 342 | label.set_visible(False) |
| 343 | ax.set_xticks([]) |
| 344 | ax.set_frame_on(False) |
| 345 | if labels is not None: |
| 346 | ax.imshow(labels[row][col], cmap="hsv", alpha=0.9, interpolation="nearest") |
| 347 | # title is e.g., Flipd(keys=keys, spatial_axis=0) |
| 348 | title = transform_name + "(" |
| 349 | for k, v in transform_args.items(): |
| 350 | title += k + "=" |
| 351 | if isinstance(v, str): |
| 352 | title += "'" + v + "'" |
| 353 | elif isinstance(v, (np.ndarray, torch.Tensor)): |
| 354 | title += "[array]" |
| 355 | elif callable(v): |
| 356 | title += "[callable]" |
| 357 | else: |
| 358 | title += str(v) |
| 359 | title += ", " |
| 360 | if len(transform_args) > 0: |
| 361 | title = title[:-2] |
| 362 | title += ")" |
| 363 | # shorten the lines |
| 364 | title = textwrap.fill(title, 50, break_long_words=False, subsequent_indent=" " * (len(transform_name) + 1)) |
| 365 | fig.suptitle(title, x=0.1, horizontalalignment="left") |
| 366 | fig.savefig(filename) |
| 367 | plt.close(fig) |
| 368 | |
| 369 |
no test coverage detected
searching dependent graphs…