efficient_sam.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import collections
  2. import threading
  3. import imgviz
  4. import numpy as np
  5. import onnxruntime
  6. import skimage
  7. from ..logger import logger
  8. from . import _utils
  9. class EfficientSam:
  10. def __init__(self, encoder_path, decoder_path):
  11. self._encoder_session = onnxruntime.InferenceSession(encoder_path)
  12. self._decoder_session = onnxruntime.InferenceSession(decoder_path)
  13. self._lock = threading.Lock()
  14. self._image_embedding_cache = collections.OrderedDict()
  15. self._thread = None
  16. def set_image(self, image: np.ndarray):
  17. with self._lock:
  18. self._image = image
  19. self._image_embedding = self._image_embedding_cache.get(
  20. self._image.tobytes()
  21. )
  22. if self._image_embedding is None:
  23. self._thread = threading.Thread(
  24. target=self._compute_and_cache_image_embedding
  25. )
  26. self._thread.start()
  27. def _compute_and_cache_image_embedding(self):
  28. with self._lock:
  29. logger.debug("Computing image embedding...")
  30. image = imgviz.rgba2rgb(self._image)
  31. batched_images = image.transpose(2, 0, 1)[None].astype(np.float32) / 255.0
  32. (self._image_embedding,) = self._encoder_session.run(
  33. output_names=None,
  34. input_feed={"batched_images": batched_images},
  35. )
  36. if len(self._image_embedding_cache) > 10:
  37. self._image_embedding_cache.popitem(last=False)
  38. self._image_embedding_cache[self._image.tobytes()] = self._image_embedding
  39. logger.debug("Done computing image embedding.")
  40. def _get_image_embedding(self):
  41. if self._thread is not None:
  42. self._thread.join()
  43. self._thread = None
  44. with self._lock:
  45. return self._image_embedding
  46. def predict_mask_from_points(self, points, point_labels):
  47. return _compute_mask_from_points(
  48. decoder_session=self._decoder_session,
  49. image=self._image,
  50. image_embedding=self._get_image_embedding(),
  51. points=points,
  52. point_labels=point_labels,
  53. )
  54. def predict_polygon_from_points(self, points, point_labels):
  55. mask = self.predict_mask_from_points(points=points, point_labels=point_labels)
  56. return _utils.compute_polygon_from_mask(mask=mask)
  57. def _compute_mask_from_points(
  58. decoder_session, image, image_embedding, points, point_labels
  59. ):
  60. input_point = np.array(points, dtype=np.float32)
  61. input_label = np.array(point_labels, dtype=np.float32)
  62. # batch_size, num_queries, num_points, 2
  63. batched_point_coords = input_point[None, None, :, :]
  64. # batch_size, num_queries, num_points
  65. batched_point_labels = input_label[None, None, :]
  66. decoder_inputs = {
  67. "image_embeddings": image_embedding,
  68. "batched_point_coords": batched_point_coords,
  69. "batched_point_labels": batched_point_labels,
  70. "orig_im_size": np.array(image.shape[:2], dtype=np.int64),
  71. }
  72. masks, _, _ = decoder_session.run(None, decoder_inputs)
  73. mask = masks[0, 0, 0, :, :] # (1, 1, 3, H, W) -> (H, W)
  74. mask = mask > 0.0
  75. MIN_SIZE_RATIO = 0.05
  76. skimage.morphology.remove_small_objects(
  77. mask, min_size=mask.sum() * MIN_SIZE_RATIO, out=mask
  78. )
  79. if 0:
  80. imgviz.io.imsave("mask.jpg", imgviz.label2rgb(mask, imgviz.rgb2gray(image)))
  81. return mask