display.py 5.3 KB

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