# Fix an error of 'ValueError: mean must have 1 elements if it is an iterable, got 3' for method 'infer_channel_dimension_format' in 'image_utils.py'
Author: davychxn
Pull request: yes

Background:
If we use 'sentence-transformers/clip-ViT-B-32' with Transformers, which has an image Tokenizer. The Tokenizer would convert Image to Numpy array first, then infer from its shape to decide if it's ChannelDimension.FIRST or ChannelDimension.LAST.

For example, we have an image, whose shape is (512, 512, 3). For a common image, the shape means that the size is 512 * 512 pixels, and it has RBG, 3 color channels.

When setting 'input_data_format',
The infer algorithm(in 'image_utils.py', 'infer_channel_dimension_format' method) would check the first and third element of the image's shape. If it's 1(Gray channel only) or 3(RBG channels), it decides from the content of the element, and set 'input_data_format' to be ChannelDimension.FIRST(the first element is 1 or 3) or ChannelDimension.LAST(the third element is 1 or 3).

But the problem is, if we have a narrow image whose shape is (1, 1000, 3), the infer algorithm would report and raise an error: 'The channel dimension is ambiguous. Got image shape (1, 1000, 3). Assuming channels are the first dimension.' 'ValueError: mean must have 1 elements if it is an iterable, got 3'

My fix is to set 'input_data_format' before the image being converted to Numpy array. If it's a PIL image, the third element of its shape must give its color channels, and 'input_data_format' must be 'ChannelDimension.LAST'.

# What does this PR do?

<!--
Congratulations! You've made it this far! You're not quite done yet though.

Once merged, your PR is going to appear in the release notes with the title you set, so make sure it's a great title that fully reflects the extent of your awesome contribution.

Then, please replace this with a description of the change and which issue is fixed (if applicable). Please also include relevant motivation and context. List any dependencies (if any) that are required for this change.

Once you're done, someone will review your PR shortly (see the section "Who can review?" below to tag some potential reviewers). They may suggest changes to make the code even better. If no one reviewed your PR after a week has passed, don't hesitate to post a new comment @-mentioning the same persons---sometimes notifications get lost.
-->

<!-- Remove if not applicable -->

Fixes # (issue)


## Before submitting
- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case).
- [ ] Did you read the [contributor guideline](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md#create-a-pull-request),
      Pull Request section?
- [ ] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link
      to it if that's the case.
- [ ] Did you make sure to update the documentation with your changes? Here are the
      [documentation guidelines](https://github.com/huggingface/transformers/tree/main/docs), and
      [here are tips on formatting docstrings](https://github.com/huggingface/transformers/tree/main/docs#writing-source-documentation).
- [ ] Did you write any new necessary tests?


## Who can review?

Anyone in the community is free to review the PR once the tests have passed. Feel free to tag
members/contributors who may be interested in your PR.

<!-- Your PR will be replied to more quickly if you can figure out the right person to tag with @

 If you know how to use git blame, that is the easiest way, otherwise, here is a rough guide of **who to tag**.
 Please tag fewer than 3 people.

Models:

- text models: @ArthurZucker
- vision models: @amyeroberts
- speech models: @sanchit-gandhi
- graph models: @clefourrier

Library:

- flax: @sanchit-gandhi
- generate: @zucchini-nlp (visual-language models) or @gante (all others)
- pipelines: @Narsil
- tensorflow: @gante and @Rocketknight1
- tokenizers: @ArthurZucker
- trainer: @muellerzr and @SunMarc

Integrations:

- deepspeed: HF Trainer/Accelerate: @muellerzr
- ray/raytune: @richardliaw, @amogkam
- Big Model Inference: @SunMarc
- quantization (bitsandbytes, autogpt): @SunMarc 

Documentation: @stevhliu and @MKhalusova

HF projects:

- accelerate: [different repo](https://github.com/huggingface/accelerate)
- datasets: [different repo](https://github.com/huggingface/datasets)
- diffusers: [different repo](https://github.com/huggingface/diffusers)
- rust tokenizers: [different repo](https://github.com/huggingface/tokenizers)

Maintained examples (not research project or legacy):

- Flax: @sanchit-gandhi
- PyTorch: See Models above and tag the person corresponding to the modality of the example.
- TensorFlow: @Rocketknight1

 -->


Comments:
![header-separator](https://github.com/user-attachments/assets/5b12b843-a586-4214-8a4c-98dc59360363)
This is an error generating image, which has a shape of (1, 1000, 3)

@amyeroberts @gante 
Would you help to review my change? Thank you. 

Hi @davychxn, thanks for opening this PR! 

Have you tried calling the image_processor with `input_data_format` set e.g.: 

```py
inputs = image_processor(images, input_data_format="channels_last")
```

The `input_data_format` argument was added for cases when there might be ambiguity and to avoid inferring 

@amyeroberts 
Thank you for your opinion.
Yes, I can use the way you mentioned in sentence-transformers' code to avoid the issue.

But it's still a defect in inferring algorithm. If we have an image with the shape of (1, xxx, 3) or (3, xxx, 1), it would raise an exception.

So, you would prefer me to fix it in sentence-transformers?

Sometimes the exception could break your training process and waste you a lot of time, could be annoying.

Say, you go through thousands of images. And external images could have undetermined shapes. Your program could be broken many times unless you use:
```
for(image in images):
    try:
        model.encode(image)
    except:
        continue
```
    

@davychxn 

> But it's still a defect in inferring algorithm. If we have an image with the shape of (1, xxx, 3) or (3, xxx, 1), it would raise an exception.

Yes, unfortunately this is very hard to get around. This is in part why the functional is called "infer" rather than "get". It would be better to pass in `input_data_format="channels_last" as this avoids doing this type inference every time the image processor is called. 

OK, @amyeroberts ,

I've submitted another PR at sentence-transformers.
I'll wait for their reply and close this PR a bit later. Thank you.

This issue has been automatically marked as stale because it has not had recent activity. If you think this still needs to be addressed please comment on this thread.

Please note that issues that do not follow the [contributing guidelines](https://github.com/huggingface/transformers/blob/main/CONTRIBUTING.md) are likely to be ignored.