def __call__(self, img: Union[np.ndarray, torch.Tensor, PILImageImage]) -> PILImageImage: """ Apply the transform to `img` and make it contiguous. """ if isinstance(img, PILImageImage): return img if isinstance(img, torch.Tensor): img = img.detach().cpu().numpy() return pil_image_fromarray(img)
from PIL.Image import Image as PILImageImage from PIL.Image import fromarray as pil_image_fromarray has_pil = True else: pil_image_fromarray, has_pil = optional_import("PIL.Image", name="fromarray") PILImageImage, _ = optional_import("PIL.Image", name="Image") im = [[1.0, 2.0], [3.0, 4.0]] TESTS = [[{"keys": "image"}, {"image": p(im)}] for p in TEST_NDARRAYS] if has_pil: TESTS.append([{ "keys": "image" }, { "image": pil_image_fromarray(np.array(im)) }]) class TestToPIL(unittest.TestCase): @parameterized.expand(TESTS) @skipUnless(has_pil, "Requires `pillow` package.") def test_values(self, input_param, test_data): result = ToPILd(**input_param)(test_data)[input_param["keys"]] self.assertTrue(isinstance(result, PILImageImage)) assert_allclose(np.array(result), test_data[input_param["keys"]], type_test=False) if __name__ == "__main__":
if TYPE_CHECKING: from PIL.Image import Image as PILImageImage from PIL.Image import fromarray as pil_image_fromarray has_pil = True else: pil_image_fromarray, has_pil = optional_import("PIL.Image", name="fromarray") PILImageImage, _ = optional_import("PIL.Image", name="Image") im = [[1.0, 2.0], [3.0, 4.0]] TESTS = [] for p in TEST_NDARRAYS: TESTS.append([p(im)]) if has_pil: TESTS.append([pil_image_fromarray(np.array(im))]) class TestToPIL(unittest.TestCase): @parameterized.expand(TESTS) @skipUnless(has_pil, "Requires `pillow` package.") def test_value(self, test_data): result = ToPIL()(test_data) self.assertTrue(isinstance(result, PILImageImage)) assert_allclose(np.array(result), test_data, type_test=False) if __name__ == "__main__": unittest.main()
def test_pil_input(self, test_data): test_data_pil = pil_image_fromarray(test_data) self.assertTrue(isinstance(test_data_pil, PILImageImage)) result = ToPIL()(test_data_pil) self.assertTrue(isinstance(result, PILImageImage)) np.testing.assert_allclose(np.array(result), test_data)