tests.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
  2. # pyre-unsafe
  3. import os
  4. import numpy as np
  5. import pytest
  6. import torch
  7. from PIL import Image
  8. from sam3.perflib.masks_ops import masks_to_boxes
  9. class TestMasksToBoxes:
  10. def test_masks_box(self):
  11. def masks_box_check(masks, expected, atol=1e-4):
  12. out = masks_to_boxes(masks, [1 for _ in range(masks.shape[0])])
  13. assert out.dtype == torch.float
  14. print("out: ", out)
  15. print("expected: ", expected)
  16. torch.testing.assert_close(
  17. out, expected, rtol=0.0, check_dtype=True, atol=atol
  18. )
  19. # Check for int type boxes.
  20. def _get_image():
  21. assets_directory = os.path.join(
  22. os.path.dirname(os.path.abspath(__file__)), "assets"
  23. )
  24. mask_path = os.path.join(assets_directory, "masks.tiff")
  25. image = Image.open(mask_path)
  26. return image
  27. def _create_masks(image, masks):
  28. for index in range(image.n_frames):
  29. image.seek(index)
  30. frame = np.array(image)
  31. masks[index] = torch.tensor(frame)
  32. return masks
  33. expected = torch.tensor(
  34. [
  35. [127, 2, 165, 40],
  36. [2, 50, 44, 92],
  37. [56, 63, 98, 100],
  38. [139, 68, 175, 104],
  39. [160, 112, 198, 145],
  40. [49, 138, 99, 182],
  41. [108, 148, 152, 213],
  42. ],
  43. dtype=torch.float,
  44. )
  45. image = _get_image()
  46. for dtype in [torch.float16, torch.float32, torch.float64]:
  47. masks = torch.zeros(
  48. (image.n_frames, image.height, image.width), dtype=dtype
  49. )
  50. masks = _create_masks(image, masks)
  51. masks_box_check(masks, expected)