From b41688cb8d8c18a9d47de2c1bd7e7bdda8fa9ad2 Mon Sep 17 00:00:00 2001 From: dcaayushd Date: Thu, 26 Nov 2026 22:04:03 +0545 Subject: [PATCH] Fix grayscale conversion for NumPy RGB inputs --- src/diffusers/image_processor.py | 9 ++++++++- tests/others/test_image_processor.py | 10 ++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/src/diffusers/image_processor.py b/src/diffusers/image_processor.py index db5233ec1225..eb7fdb896d18 100644 --- a/src/diffusers/image_processor.py +++ b/src/diffusers/image_processor.py @@ -644,7 +644,14 @@ def preprocess( supported_formats = (PIL.Image.Image, np.ndarray, torch.Tensor) # Expand the missing dimension for 3-dimensional pytorch tensor or numpy array that represents grayscale image - if self.config.do_convert_grayscale and isinstance(image, (torch.Tensor, np.ndarray)) and image.ndim == 3: + if ( + self.config.do_convert_grayscale + and isinstance(image, np.ndarray) + and image.ndim == 3 + and image.shape[-1] in (3, 4) + ): + image = np.dot(image[..., :3], np.array([0.299, 0.587, 0.114], dtype=np.float32)) + elif self.config.do_convert_grayscale and isinstance(image, (torch.Tensor, np.ndarray)) and image.ndim == 3: if isinstance(image, torch.Tensor): # if image is a pytorch tensor could have 2 possible shapes: # 1. batch x height x width: we should insert the channel dimension at position 1 diff --git a/tests/others/test_image_processor.py b/tests/others/test_image_processor.py index 05cbb8a27a2d..fbb94bb0427e 100644 --- a/tests/others/test_image_processor.py +++ b/tests/others/test_image_processor.py @@ -126,6 +126,16 @@ def test_preprocess_input_3d(self): assert np.abs(out_pt_4d - out_pt_3d).max() < 1e-6 assert np.abs(out_np_4d - out_np_3d).max() < 1e-6 + def test_preprocess_rgb_numpy_to_grayscale(self): + image_processor = VaeImageProcessor(do_resize=False, do_normalize=False, do_convert_grayscale=True) + image = np.random.rand(8, 8, 3).astype(np.float32) + + output = image_processor.preprocess(image) + expected = np.einsum("hwc,c->hw", image, np.array([0.299, 0.587, 0.114], dtype=np.float32)) + + assert output.shape == (1, 1, 8, 8) + np.testing.assert_allclose(output[0, 0].numpy(), expected, atol=1e-7) + def test_preprocess_input_list(self): image_processor = VaeImageProcessor(do_resize=False, do_normalize=False)