display.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. #!/usr/bin/env python
  2. if __name__ != '__main__': raise Exception("Do not import me!")
  3. from argparse import ArgumentParser
  4. import logging
  5. import numpy as np
  6. from annotations import NAB_Annotations, CUB_Annotations
  7. from dataset import Dataset
  8. from dataset.utils import reveal_parts, uniform_parts, \
  9. random_select, \
  10. visible_part_locs, visible_crops
  11. import matplotlib.pyplot as plt
  12. def init_logger(args):
  13. fmt = "%(levelname)s - [%(asctime)s] %(filename)s:%(lineno)d [%(funcName)s]: %(message)s"
  14. logging.basicConfig(
  15. format=fmt,
  16. level=getattr(logging, args.loglevel.upper(), logging.DEBUG),
  17. filename=args.logfile or None,
  18. filemode="w")
  19. def plot_crops(crops, title, scatter_mid=False):
  20. fig = plt.figure(figsize=(16,9))
  21. fig.suptitle(title, fontsize=16)
  22. n_crops = crops.shape[0]
  23. rows = int(np.ceil(np.sqrt(n_crops)))
  24. cols = int(np.ceil(n_crops / rows))
  25. for j, crop in enumerate(crops, 1):
  26. ax = fig.add_subplot(rows, cols, j)
  27. ax.imshow(crop)
  28. ax.axis("off")
  29. if scatter_mid:
  30. middle_h, middle_w = crop.shape[0] / 2, crop.shape[1] / 2
  31. ax.scatter(middle_w, middle_h, marker="x")
  32. def main(args):
  33. init_logger(args)
  34. annotation_cls = dict(
  35. nab=NAB_Annotations,
  36. cub=CUB_Annotations)
  37. logging.info("Loading \"{}\" annnotations from \"{}\"".format(args.dataset, args.data))
  38. annot = annotation_cls.get(args.dataset.lower())(args.data)
  39. uuids = getattr(annot, "{}_uuids".format(args.subset.lower()))
  40. data = Dataset(
  41. uuids=uuids, annotations=annot,
  42. uniform_parts=args.uniform_parts,
  43. crop_to_bb=args.crop_to_bb,
  44. crop_uniform=args.crop_uniform,
  45. parts_in_bb=args.parts_in_bb,
  46. rnd_select=args.rnd,
  47. ratio=args.ratio,
  48. seed=args.seed
  49. )
  50. n_images = len(data)
  51. logging.info("Found {} images in the {} subset".format(n_images, args.subset))
  52. for i in range(n_images):
  53. if i + 1 <= args.start: continue
  54. im, parts, label = data[i]
  55. idxs, xy = visible_part_locs(parts)
  56. part_crops = visible_crops(im, parts, ratio=args.ratio)
  57. if args.rnd:
  58. selected = parts[:, -1].astype(bool)
  59. parts[selected, -1] = 0
  60. parts[np.logical_not(selected), -1] = 1
  61. action_crops = visible_crops(im, parts, ratio=args.ratio)
  62. logging.debug(label)
  63. logging.debug(idxs)
  64. logging.debug(xy)
  65. fig1 = plt.figure(figsize=(16,9))
  66. ax = fig1.add_subplot(2,1,1)
  67. ax.imshow(im)
  68. ax.set_title("Visible Parts")
  69. ax.scatter(*xy, marker="x", c=idxs)
  70. ax.axis("off")
  71. ax = fig1.add_subplot(2,1,2)
  72. ax.set_title("{}selected parts".format("randomly " if args.rnd else ""))
  73. ax.imshow(reveal_parts(im, xy, ratio=args.ratio))
  74. # ax.scatter(*xy, marker="x", c=idxs)
  75. ax.axis("off")
  76. plot_crops(part_crops, "Selected parts")
  77. if args.rnd:
  78. plot_crops(action_crops, "Actions")
  79. plt.show()
  80. plt.close()
  81. if i+1 >= args.start + args.n_images: break
  82. parser = ArgumentParser()
  83. parser.add_argument("data",
  84. help="Folder containing the dataset with images and annotation files",
  85. type=str)
  86. parser.add_argument("--dataset",
  87. help="Possible datasets: NAB, CUB",
  88. choices=["cub", "nab"],
  89. default="nab", type=str)
  90. parser.add_argument("--subset",
  91. help="Possible subsets: train, test",
  92. choices=["train", "test"],
  93. default="train", type=str)
  94. parser.add_argument("--start", "-s",
  95. help="Image id to start with",
  96. type=int, default=0)
  97. parser.add_argument("--n_images", "-n",
  98. help="Number of images to display",
  99. type=int, default=10)
  100. parser.add_argument("--ratio",
  101. help="Part extraction ratio",
  102. type=float, default=.2)
  103. parser.add_argument("--rnd",
  104. help="select random subset of present parts",
  105. action="store_true")
  106. parser.add_argument("--uniform_parts", "-u",
  107. help="Do not use GT parts, but sample parts uniformly from the image",
  108. action="store_true")
  109. parser.add_argument("--crop_to_bb",
  110. help="Crop image to the bounding box",
  111. action="store_true")
  112. parser.add_argument("--crop_uniform",
  113. help="Try to extend the bounding box to same height and width",
  114. action="store_true")
  115. parser.add_argument("--parts_in_bb",
  116. help="Only display parts, that are inside the bounding box",
  117. action="store_true")
  118. parser.add_argument(
  119. '--logfile', type=str, default='',
  120. help='File for logging output')
  121. parser.add_argument(
  122. '--loglevel', type=str, default='INFO',
  123. help='logging level. see logging module for more information')
  124. parser.add_argument(
  125. '--seed', type=int, default=12311123,
  126. help='random seed')
  127. main(parser.parse_args())