display.py 5.3 KB

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