visualize_attention_map_1.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. def visualize_grid_attention(img_path, save_path, attention_mask, ratio=0.5, save_image=True, save_original_image=True, quality=100):
  2. """
  3. img_path: where to load the image
  4. save_path: where to save the image
  5. attention_mask: the 2-D attention mask on your image, e.g: np.array (h, w) or (w, h)
  6. ratio: scaling factor to scale the output h and w
  7. quality: save image quality
  8. """
  9. print("load image from: " + img_path)
  10. img = Image.open(img_path)
  11. img_h, img_w = img.size[0], img.size[1]
  12. plt.subplots(nrows=1, ncols=1, figsize=(0.02 * img_h, 0.02 * img_w))
  13. # scale the image
  14. img_h, img_w = int(img.size[0] * ratio), int(img.size[1] * ratio)
  15. img = img.resize((img_h, img_w))
  16. plt.imshow(img, alpha=1)
  17. plt.axis('off')
  18. # normalize the attention map
  19. mask = cv2.resize(attention_mask, (img_h, img_w)) # you may change the (img_w, img_h) order to adjust the attention mask
  20. normed_mask = mask / mask.max()
  21. normed_mask = cv2.resize(normed_mask, img.size)[..., np.newaxis]
  22. # put the attention map on the original image
  23. result = (img * normed_mask).astype("uint8")
  24. plt.imshow(result, alpha=1)
  25. # save image
  26. if save_image:
  27. # build save path
  28. if not os.path.exists(save_path):
  29. os.mkdir(save_path)
  30. assert save_image is not None, "you need to set where to store the picture"
  31. img_name = img_path.split('/')[-1].split('.')[0] + "_with_attention.jpg"
  32. img_with_attention_save_path = os.path.join(save_path, img_name)
  33. # pre-process before saving
  34. print("save image to: " + save_path)
  35. plt.axis('off')
  36. plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
  37. plt.margins(0, 0)
  38. plt.savefig(img_with_attention_save_path, dpi=quality)
  39. # save original image
  40. if save_original_image:
  41. # build save path
  42. if not os.path.exists(save_path):
  43. os.mkdir(save_path)
  44. print("save original image at the same time")
  45. img_name = img_path.split('/')[-1].split('.')[0] + "_original.jpg"
  46. original_image_save_path = os.path.join(save_path, img_name)
  47. img.save(original_image_save_path, quality=quality)