|
| 1 | +import os |
| 2 | + |
| 3 | +import numpy as np |
| 4 | +from absl.testing import parameterized |
| 5 | + |
| 6 | +from keras.src import testing |
| 7 | +from keras.src.utils import img_to_array |
| 8 | +from keras.src.utils import load_img |
| 9 | +from keras.src.utils import save_img |
| 10 | + |
| 11 | + |
| 12 | +class SaveImgTest(testing.TestCase, parameterized.TestCase): |
| 13 | + @parameterized.named_parameters( |
| 14 | + ("rgb_explicit_format", (50, 50, 3), "rgb.jpg", "jpg", True), |
| 15 | + ("rgba_explicit_format", (50, 50, 4), "rgba.jpg", "jpg", True), |
| 16 | + ("rgb_inferred_format", (50, 50, 3), "rgb_inferred.jpg", None, False), |
| 17 | + ("rgba_inferred_format", (50, 50, 4), "rgba_inferred.jpg", None, False), |
| 18 | + ) |
| 19 | + def test_save_jpg(self, shape, name, file_format, use_explicit_format): |
| 20 | + tmp_dir = self.get_temp_dir() |
| 21 | + path = os.path.join(tmp_dir, name) |
| 22 | + |
| 23 | + img = np.random.randint(0, 256, size=shape, dtype=np.uint8) |
| 24 | + |
| 25 | + # Test the actual inferred case - don't pass file_format at all |
| 26 | + if use_explicit_format: |
| 27 | + save_img(path, img, file_format=file_format) |
| 28 | + else: |
| 29 | + save_img(path, img) # Let it infer from path |
| 30 | + |
| 31 | + self.assertTrue(os.path.exists(path)) |
| 32 | + |
| 33 | + # Verify saved image is correctly converted to RGB if needed |
| 34 | + loaded_img = load_img(path) |
| 35 | + loaded_array = img_to_array(loaded_img) |
| 36 | + self.assertEqual(loaded_array.shape, (50, 50, 3)) |
0 commit comments