'DonutImageProcessor' object has no attribute 'to_pil_image'
Author: andysingal
Pull request: no

### System Info

```
!pip install -q git+https://github.com/huggingface/transformers.git
!pip install -q datasets sentencepiece tensorboard
!sudo apt-get install git-lfs --yes
!pip install -q accelerate -U
```
for reference: https://colab.research.google.com/drive/1CVhL9c3yoJ5IE8-5DG7W7AofmyA5f7aP?usp=sharing

### Who can help?

@amyeroberts @pacman

### Information

- [ ] The official example scripts
- [ ] My own modified scripts

### Tasks

- [ ] An officially supported task in the `examples` folder (such as GLUE/SQuAD, ...)
- [ ] My own task or dataset (give details below)

### Reproduction

```
import re
import transformers
from PIL import Image
from transformers import DonutProcessor, VisionEncoderDecoderModel
import torch
import random
import numpy as np

# hidde logs
transformers.logging.disable_default_handler()


# Load our model from Hugging Face
processor = DonutProcessor.from_pretrained("Andyrasika/donut-base-sroie")
model = VisionEncoderDecoderModel.from_pretrained("Andyrasika/donut-base-sroie")

# Move model to GPU
device = "cuda" if torch.cuda.is_available() else "cpu"
model.to(device)

# Load random document image from the test set
test_sample = processed_dataset["test"][random.randint(1, 50)]

def run_prediction(sample, model=model, processor=processor):
    # prepare inputs
    pixel_values = torch.tensor(test_sample["pixel_values"]).unsqueeze(0)
    task_prompt = "
"
    decoder_input_ids = processor.tokenizer(task_prompt, add_special_tokens=False, return_tensors="pt").input_ids

    # run inference
    outputs = model.generate(
        pixel_values.to(device),
        decoder_input_ids=decoder_input_ids.to(device),
        max_length=model.decoder.config.max_position_embeddings,
        early_stopping=True,
        pad_token_id=processor.tokenizer.pad_token_id,
        eos_token_id=processor.tokenizer.eos_token_id,
        use_cache=True,
        num_beams=1,
        bad_words_ids=[[processor.tokenizer.unk_token_id]],
        return_dict_in_generate=True,
    )

    # process output
    prediction = processor.batch_decode(outputs.sequences)[0]
    prediction = processor.token2json(prediction)

    # load reference target
    target = processor.token2json(test_sample["target_sequence"])
    return prediction, target

prediction, target = run_prediction(test_sample)
print(f"Reference:\n {target}")
print(f"Prediction:\n {prediction}")
processor.feature_extractor.to_pil_image(np.array(test_sample["pixel_values"])).resize((350,600))
```
giving error:
```
Downloading (…)rocessor_config.json: 100%
420/420 [00:00<00:00, 34.6kB/s]
Downloading (…)okenizer_config.json: 100%
510/510 [00:00<00:00, 42.5kB/s]
Downloading (…)tencepiece.bpe.model: 100%
1.30M/1.30M [00:00<00:00, 4.16MB/s]
Downloading (…)/main/tokenizer.json: 100%
4.01M/4.01M [00:00<00:00, 12.7MB/s]
Downloading (…)in/added_tokens.json: 100%
257/257 [00:00<00:00, 22.3kB/s]
Downloading (…)cial_tokens_map.json: 100%
485/485 [00:00<00:00, 45.3kB/s]
Downloading (…)lve/main/config.json: 100%
4.89k/4.89k [00:00<00:00, 369kB/s]
Downloading pytorch_model.bin: 100%
809M/809M [00:14<00:00, 61.1MB/s]
Downloading (…)neration_config.json: 100%
165/165 [00:00<00:00, 14.2kB/s]
/usr/local/lib/python3.10/dist-packages/transformers/generation/utils.py:1417: UserWarning: You have modified the pretrained model configuration to control generation. This is a deprecated strategy to control generation and will be removed soon, in a future version. Please use a generation configuration file (see https://huggingface.co/docs/transformers/main_classes/text_generation )
  warnings.warn(
/usr/local/lib/python3.10/dist-packages/transformers/generation/configuration_utils.py:399: UserWarning: `num_beams` is set to 1. However, `early_stopping` is set to `True` -- this flag is only used in beam-based generation modes. You should set `num_beams>1` or unset `early_stopping`.
  warnings.warn(
Reference:
 {'total': '19.00', 'date': '04-05-18', 'company': 'C W KHOO HARDWARE SDN BHD', 'address': 'NO.50, JALAN PBS 14/11, KAWASAN PERINDUSTRIAN BUKIT SERDANG,'}
Prediction:
 {'total': '19.00', 'date': '04-05-18', 'company': 'C W KHOO HARDWARE SDN BHD', 'address': 'NO.50, JALAN PBS 14/11, KAWASAN PERINDUSTRIAN BUKIT SERDANG,'}
/usr/local/lib/python3.10/dist-packages/transformers/models/donut/processing_donut.py:189: FutureWarning: `feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.
  warnings.warn(
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
[<ipython-input-17-c77c791b55f7>](https://localhost:8080/#) in <cell line: 55>()
     53 print(f"Reference:\n {target}")
     54 print(f"Prediction:\n {prediction}")
---> 55 processor.feature_extractor.to_pil_image(np.array(test_sample["pixel_values"])).resize((350,600))

AttributeError: 'DonutImageProcessor' object has no attribute 'to_pil_image'
```

### Expected behavior

needs to display image

Comments:
Hi @andysingal, thanks for raising this issue! 

Could you share where the notebook is from? i.e. is it an official example from within the HF ecosystem? I'm asking so I know any places that will need to be updated. 

The class `processor.feature_extractor` doesn't have the method `to_pil_image`. There is a method available in the image transforms library which performs the same functionality:

```python
from transformers.image_transforms import to_pil_image

...

print(f"Prediction:\n {prediction}")
to_pil_image(np.array(test_sample["pixel_values"])).resize((350,600))
```

@amyeroberts I think this might be the article that provoked the issue: https://www.philschmid.de/fine-tuning-donut#4-fine-tune-and-evaluate-donut-model (I notice the variable names and arguments to `resize` are the same).

Your suggestion:
```
from transformers.image_transforms import to_pil_image
to_pil_image(np.array(test_sample["pixel_values"])).resize((350,600))
```

Yields the issue: 

ValueError: The image to be converted to a PIL image contains values outside the range [0, 1], got [-1.0, 1.0] which cannot be converted to uint8.

Which suggests to me that the 2 methods might not be equivalent, or some breaking change happened between the publish date of the article and the current API.

This might be outside your work responsibility, but I post here hoping you might have another suggestion :pray: 

@hauthorn - thanks highlighting the article. 

Yes, the `to_pil_image` function in the image_transforms method is derived from the `to_pil_image` method that the deprecated feature extractors used. There were some checks added to the inputs but the logic remains the same. Previously, it would blindly rescale by 255 if it had floating values and convert to `uint8` before converting to a PIL.Image. Now, it checks the input to make sure this is valid - which is what's raising the exception now. As the image has values between [-1, 1], these would be rescaled to [-255, 255], which when casting to uint8 will set all of the values less that 0 to 0. 

In this case, the pixel values need to be manually shifted and rescaled: 

```python
from transformers import to_pil_image

pixel_values = test_sample["pixel_values"]
# Rescale values between 0-1
pixel_values = (pixel_values + 1) / 2

to_pil_image(np.array(test_sample["pixel_values"])).resize((350,600))
```


@andysingal were you able to solve the problem? I'm having exactly the same error and I can't solve it.

Thank you so much!

@erikaxenia 

Hi, Erika, et al.,

had similar issue, 

this is what worked for me
```
pixel_values = np.squeeze(test_sample["pixel_values"])
pixel_values = (pixel_values + 1) / 2


to_pil_image(pixel_values)
```

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.