features.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import numpy as np
  2. from os.path import isfile
  3. from . import BaseMixin
  4. class PreExtractedFeaturesMixin(BaseMixin):
  5. def __size_check(self):
  6. assert len(self.features) == len(self), \
  7. "Number of features ({}) does not match the number of images ({})!".format(
  8. len(self.features), len(self)
  9. )
  10. def __init__(self, features=None, *args, **kw):
  11. super(PreExtractedFeaturesMixin, self).__init__(*args, **kw)
  12. self.features = None
  13. if features is not None and isfile(features):
  14. self.features = self.load_features(features)
  15. self.__size_check()
  16. def load_features(self, features_file):
  17. """
  18. Default feature loading from a file.
  19. If you desire another feature loading logic,
  20. subclass this mixin and override this method.
  21. """
  22. try:
  23. cont = np.load(features_file)
  24. return cont["features"]
  25. except Exception as e:
  26. msg = "Error occured while reading features: \"{}\". ".format(e) + \
  27. "If you want another feature loading logic, override this method!"
  28. raise ValueError(msg)
  29. def get_example(self, i):
  30. im_obj = super(PreExtractedFeaturesMixin, self).get_example(i)
  31. if self.features is not None:
  32. im_obj.feature = self.features[i]
  33. return im_obj