Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/diffusers/image_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 10 additions & 0 deletions tests/others/test_image_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down