blob.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # --------------------------------------------------------
  2. # Fast R-CNN
  3. # Copyright (c) 2015 Microsoft
  4. # Licensed under The MIT License [see LICENSE for details]
  5. # Written by Ross Girshick
  6. # --------------------------------------------------------
  7. """Blob helper functions."""
  8. from __future__ import absolute_import
  9. from __future__ import division
  10. from __future__ import print_function
  11. import numpy as np
  12. import cv2
  13. def im_list_to_blob(ims):
  14. """Convert a list of images into a network input.
  15. Assumes images are already prepared (means subtracted, BGR order, ...).
  16. """
  17. max_shape = np.array([im.shape for im in ims]).max(axis=0)
  18. num_images = len(ims)
  19. blob = np.zeros((num_images, max_shape[0], max_shape[1], 3),
  20. dtype=np.float32)
  21. for i in range(num_images):
  22. im = ims[i]
  23. blob[i, 0:im.shape[0], 0:im.shape[1], :] = im
  24. return blob
  25. def prep_im_for_blob(im, pixel_means, target_size, max_size):
  26. """Mean subtract and scale an image for use in a blob."""
  27. im = im.astype(np.float32, copy=False)
  28. im -= pixel_means
  29. im_shape = im.shape
  30. im_size_min = np.min(im_shape[0:2])
  31. im_size_max = np.max(im_shape[0:2])
  32. im_scale = float(target_size) / float(im_size_min)
  33. # Prevent the biggest axis from being more than MAX_SIZE
  34. if np.round(im_scale * im_size_max) > max_size:
  35. im_scale = float(max_size) / float(im_size_max)
  36. im = cv2.resize(im, None, None, fx=im_scale, fy=im_scale,
  37. interpolation=cv2.INTER_LINEAR)
  38. return im, im_scale