train_bow.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. # Approach 3: Local features
  2. # This script is used for generating a BOW vocabulary using
  3. # densely sampeled SIFT features on Lapse images.
  4. # See eval_bow.py for evaluation.
  5. import argparse
  6. import os
  7. import numpy as np
  8. from timeit import default_timer as timer
  9. from datetime import timedelta
  10. from py.Dataset import Dataset
  11. from py.LocalFeatures import extract_descriptors, generate_dictionary_from_descriptors, generate_bow_features, pick_random_descriptors
  12. def main():
  13. parser = argparse.ArgumentParser(description="BOW train script")
  14. parser.add_argument("dataset_dir", type=str, help="Directory of the dataset containing all session folders")
  15. parser.add_argument("session_name", type=str, help="Name of the session to use for Lapse images (e.g. marten_01)")
  16. parser.add_argument("--clusters", type=int, help="Number of clusters / BOW vocabulary size", default=1024)
  17. parser.add_argument("--step_size", type=int, help="DSIFT keypoint step size. Smaller step size = more keypoints.", default=30)
  18. parser.add_argument("--keypoint_size", type=int, help="DSIFT keypoint size. Defaults to step_size.", default=-1)
  19. parser.add_argument("--include_motion", action="store_true", help="Include motion images for training.")
  20. parser.add_argument("--random_prototypes", action="store_true", help="Pick random prototype vectors instead of doing kmeans.")
  21. parser.add_argument("--num_vocabularies", type=int, help="Number of vocabularies to generate if random prototype choosing is enabled.", default=10)
  22. args = parser.parse_args()
  23. if args.keypoint_size <= 0:
  24. args.keypoint_size = args.step_size
  25. print(f"Using keypoint size {args.keypoint_size} with step size {args.step_size}.")
  26. ds = Dataset(args.dataset_dir)
  27. session = ds.create_session(args.session_name)
  28. save_dir = f"./bow_train_NoBackup/{session.name}"
  29. suffix = ""
  30. if args.include_motion:
  31. suffix += "_motion"
  32. print("Including motion data for prototype selection!")
  33. if args.random_prototypes:
  34. suffix += "_random"
  35. print("Picking random prototypes instead of using kmeans!")
  36. lapse_dscs_file = os.path.join(save_dir, f"lapse_dscs_{args.step_size}_{args.keypoint_size}.npy")
  37. motion_dscs_file = os.path.join(save_dir, f"motion_dscs_{args.step_size}_{args.keypoint_size}.npy")
  38. dictionary_file = os.path.join(save_dir, f"bow_dict_{args.step_size}_{args.keypoint_size}_{args.clusters}{suffix}.npy")
  39. train_feat_file = os.path.join(save_dir, f"bow_train_{args.step_size}_{args.keypoint_size}_{args.clusters}{suffix}.npy")
  40. # Lapse DSIFT descriptors
  41. if os.path.isfile(lapse_dscs_file):
  42. if os.path.isfile(dictionary_file):
  43. # if dictionary file already exists, we don't need the lapse descriptors
  44. print(f"{dictionary_file} already exists, skipping lapse descriptor extraction...")
  45. else:
  46. print(f"{lapse_dscs_file} already exists, loading lapse descriptors from file... ", end="")
  47. lapse_dscs = np.load(lapse_dscs_file)
  48. assert lapse_dscs.shape[-1] == 128
  49. lapse_dscs = lapse_dscs.reshape(-1, 128)
  50. print(f"Loaded {len(lapse_dscs)} lapse descriptors!")
  51. else:
  52. # Step 1 - extract dense SIFT descriptors
  53. print("Extracting lapse descriptors...")
  54. lapse_dscs = extract_descriptors(list(session.generate_lapse_images()), kp_step=args.step_size, kp_size=args.keypoint_size)
  55. os.makedirs(save_dir, exist_ok=True)
  56. np.save(lapse_dscs_file, lapse_dscs)
  57. # Motion DSIFT descriptors
  58. if args.include_motion:
  59. if os.path.isfile(motion_dscs_file):
  60. if os.path.isfile(dictionary_file):
  61. # if dictionary file already exists, we don't need the descriptors
  62. print(f"{dictionary_file} already exists, skipping motion descriptor extraction...")
  63. else:
  64. print(f"{motion_dscs_file} already exists, loading motion descriptors from file...", end="")
  65. motion_dscs = np.load(motion_dscs_file)
  66. assert motion_dscs.shape[-1] == 128
  67. motion_dscs = motion_dscs.reshape(-1, 128)
  68. print(f"Loaded {len(motion_dscs)} motion descriptors!")
  69. lapse_dscs = np.concatenate([lapse_dscs, motion_dscs])
  70. else:
  71. # Step 1b - extract dense SIFT descriptors from motion images
  72. print("Extracting motion descriptors...")
  73. motion_dscs = extract_descriptors(list(session.generate_motion_images()), kp_step=args.step_size, kp_size=args.keypoint_size)
  74. os.makedirs(save_dir, exist_ok=True)
  75. np.save(motion_dscs_file, motion_dscs)
  76. lapse_dscs = np.concatenate([lapse_dscs, motion_dscs])
  77. # BOW dictionary
  78. if os.path.isfile(dictionary_file):
  79. print(f"{dictionary_file} already exists, loading BOW dictionary from file...")
  80. dictionaries = np.load(dictionary_file)
  81. else:
  82. # Step 2 - create BOW dictionary from Lapse SIFT descriptors
  83. print(f"Creating BOW vocabulary with {args.clusters} clusters from {len(lapse_dscs)} descriptors...")
  84. start_time = timer()
  85. if args.random_prototypes:
  86. dictionaries = np.array([pick_random_descriptors(lapse_dscs, args.clusters) for i in range(args.num_vocabularies)])
  87. else:
  88. dictionaries = np.array([generate_dictionary_from_descriptors(lapse_dscs, args.clusters)])
  89. end_time = timer()
  90. delta_time = timedelta(seconds=end_time-start_time)
  91. print(f"Clustering took {delta_time}.")
  92. np.save(dictionary_file, dictionaries)
  93. # Extract Lapse BOW features using vocabulary (train data)
  94. if os.path.isfile(train_feat_file):
  95. print(f"{train_feat_file} already exists, skipping lapse BOW feature extraction...")
  96. else:
  97. # Step 3 - calculate training data (BOW features of Lapse images)
  98. print(f"Extracting BOW features from Lapse images...")
  99. features = [feat for _, feat in generate_bow_features(list(session.generate_lapse_images()), dictionaries, kp_step=args.step_size, kp_size=args.keypoint_size)]
  100. np.save(train_feat_file, features)
  101. print("Complete!")
  102. if __name__ == "__main__":
  103. main()