transforms.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # All rights reserved.
  3. # This source code is licensed under the license found in the
  4. # LICENSE file in the root directory of this source tree.
  5. import torch
  6. import torch.nn as nn
  7. import torch.nn.functional as F
  8. from torchvision.transforms import Normalize, Resize, ToTensor
  9. class SAM2Transforms(nn.Module):
  10. def __init__(
  11. self, resolution, mask_threshold, max_hole_area=0.0, max_sprinkle_area=0.0
  12. ):
  13. """
  14. Transforms for SAM2.
  15. """
  16. super().__init__()
  17. self.resolution = resolution
  18. self.mask_threshold = mask_threshold
  19. self.max_hole_area = max_hole_area
  20. self.max_sprinkle_area = max_sprinkle_area
  21. self.mean = [0.485, 0.456, 0.406]
  22. self.std = [0.229, 0.224, 0.225]
  23. self.to_tensor = ToTensor()
  24. self.transforms = torch.jit.script(
  25. nn.Sequential(
  26. Resize((self.resolution, self.resolution)),
  27. Normalize(self.mean, self.std),
  28. )
  29. )
  30. def __call__(self, x):
  31. x = self.to_tensor(x)
  32. return self.transforms(x)
  33. def forward_batch(self, img_list):
  34. img_batch = [self.transforms(self.to_tensor(img)) for img in img_list]
  35. img_batch = torch.stack(img_batch, dim=0)
  36. return img_batch
  37. def transform_coords(
  38. self, coords: torch.Tensor, normalize=False, orig_hw=None
  39. ) -> torch.Tensor:
  40. """
  41. Expects a torch tensor with length 2 in the last dimension. The coordinates can be in absolute image or normalized coordinates,
  42. If the coords are in absolute image coordinates, normalize should be set to True and original image size is required.
  43. Returns
  44. Un-normalized coordinates in the range of [0, 1] which is expected by the SAM2 model.
  45. """
  46. if normalize:
  47. assert orig_hw is not None
  48. h, w = orig_hw
  49. coords = coords.clone()
  50. coords[..., 0] = coords[..., 0] / w
  51. coords[..., 1] = coords[..., 1] / h
  52. coords = coords * self.resolution # unnormalize coords
  53. return coords
  54. def transform_boxes(
  55. self, boxes: torch.Tensor, normalize=False, orig_hw=None
  56. ) -> torch.Tensor:
  57. """
  58. Expects a tensor of shape Bx4. The coordinates can be in absolute image or normalized coordinates,
  59. if the coords are in absolute image coordinates, normalize should be set to True and original image size is required.
  60. """
  61. boxes = self.transform_coords(boxes.reshape(-1, 2, 2), normalize, orig_hw)
  62. return boxes
  63. def postprocess_masks(self, masks: torch.Tensor, orig_hw) -> torch.Tensor:
  64. """
  65. Perform PostProcessing on output masks.
  66. """
  67. from sam2.utils.misc import get_connected_components
  68. masks = masks.float()
  69. if self.max_hole_area > 0:
  70. # Holes are those connected components in background with area <= self.fill_hole_area
  71. # (background regions are those with mask scores <= self.mask_threshold)
  72. mask_flat = masks.flatten(0, 1).unsqueeze(1) # flatten as 1-channel image
  73. labels, areas = get_connected_components(mask_flat <= self.mask_threshold)
  74. is_hole = (labels > 0) & (areas <= self.max_hole_area)
  75. is_hole = is_hole.reshape_as(masks)
  76. # We fill holes with a small positive mask score (10.0) to change them to foreground.
  77. masks = torch.where(is_hole, self.mask_threshold + 10.0, masks)
  78. if self.max_sprinkle_area > 0:
  79. labels, areas = get_connected_components(mask_flat > self.mask_threshold)
  80. is_hole = (labels > 0) & (areas <= self.max_sprinkle_area)
  81. is_hole = is_hole.reshape_as(masks)
  82. # We fill holes with negative mask score (-10.0) to change them to background.
  83. masks = torch.where(is_hole, self.mask_threshold - 10.0, masks)
  84. masks = F.interpolate(masks, orig_hw, mode="bilinear", align_corners=False)
  85. return masks