

'''simple docstring'''

import json
import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import evaluate
import numpy as np
import torch
from datasets import load_dataset
from huggingface_hub import hf_hub_download
from PIL import Image
from torch import nn
from torchvision import transforms
from torchvision.transforms import functional

import transformers
from transformers import (
    AutoConfig,
    AutoImageProcessor,
    AutoModelForSemanticSegmentation,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
lowerCAmelCase_     =      logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.31.0")

require_version("datasets>=2.0.0", "To fix: pip install -r examples/pytorch/semantic-segmentation/requirements.txt")

def      __magic_name__							(			A       , A       , A=0				)      ->		int:
	snake_case							=					(size, size) if isinstance(A       , A				) else size
	snake_case			,			snake_case							=					img.size
	snake_case							=					size[1] - original_height if original_height < size[1] else 0
	snake_case							=					size[0] - original_width if original_width < size[0] else 0
	snake_case							=					functional.pad(A       , (0, 0, pad_width, pad_height)       , fill=A				)
	return img







class lowerCamelCase   :

				def __init__(       self,						lowercase_ )    ->							Optional[Any]:
					snake_case							=					transforms






				def __call__(       self,						lowercase_,						lowercase_ )    ->							Optional[int]:
					for t in self.transforms:
						snake_case			,			snake_case							=					t(A__,						A__ )
					return image, target







class lowerCamelCase   :

				def __init__(       self )    ->							Tuple:
					pass






				def __call__(       self,						lowercase_,						lowercase_ )    ->							Union[str, Any]:
					return image, target







class lowerCamelCase   :

				def __init__(       self,						lowercase_ )    ->							Optional[int]:
					snake_case							=					size






				def __call__(       self,						lowercase_,						lowercase_ )    ->							Optional[Any]:
					snake_case							=					functional.resize(A__,						self.size )
					snake_case							=					functional.resize(A__,						self.size,						interpolation=transforms.InterpolationMode.NEAREST )
					return image, target







class lowerCamelCase   :

				def __init__(       self,						lowercase_,						lowercase_=None )    ->							Tuple:
					snake_case							=					min_size
					if max_size is None:
						snake_case							=					min_size
					snake_case							=					max_size






				def __call__(       self,						lowercase_,						lowercase_ )    ->							Tuple:
					snake_case							=					random.randint(self.min_size,						self.max_size )
					snake_case							=					functional.resize(A__,						A__ )
					snake_case							=					functional.resize(A__,						A__,						interpolation=transforms.InterpolationMode.NEAREST )
					return image, target







class lowerCamelCase   :

				def __init__(       self,						lowercase_ )    ->							List[str]:
					snake_case							=					size if isinstance(A__,						A__ ) else (size, size)






				def __call__(       self,						lowercase_,						lowercase_ )    ->							List[str]:
					snake_case							=					pad_if_smaller(A__,						self.size )
					snake_case							=					pad_if_smaller(A__,						self.size,						fill=255 )
					snake_case							=					transforms.RandomCrop.get_params(A__,						self.size )
					snake_case							=					functional.crop(A__,						*A__ )
					snake_case							=					functional.crop(A__,						*A__ )
					return image, target







class lowerCamelCase   :

				def __init__(       self,						lowercase_ )    ->							Optional[Any]:
					snake_case							=					flip_prob






				def __call__(       self,						lowercase_,						lowercase_ )    ->							Dict:
					if random.random() < self.flip_prob:
						snake_case							=					functional.hflip(A__ )
						snake_case							=					functional.hflip(A__ )
					return image, target







class lowerCamelCase   :

				def __call__(       self,						lowercase_,						lowercase_ )    ->							Optional[int]:
					snake_case							=					functional.pil_to_tensor(A__ )
					snake_case							=					torch.as_tensor(np.array(A__ ),						dtype=torch.intaa )
					return image, target







class lowerCamelCase   :

				def __init__(       self,						lowercase_ )    ->							Tuple:
					snake_case							=					dtype






				def __call__(       self,						lowercase_,						lowercase_ )    ->							List[Any]:
					snake_case							=					functional.convert_image_dtype(A__,						self.dtype )
					return image, target







class lowerCamelCase   :

				def __init__(       self,						lowercase_,						lowercase_ )    ->							Optional[Any]:
					snake_case							=					mean
					snake_case							=					std






				def __call__(       self,						lowercase_,						lowercase_ )    ->							Any:
					snake_case							=					functional.normalize(A__,						mean=self.mean,						std=self.std )
					return image, target







class lowerCamelCase   :

				def __call__(       self,						lowercase_,						lowercase_ )    ->							Union[str, Any]:
					if not isinstance(A__,						np.ndarray ):
						snake_case							=					np.array(A__ ).astype(np.uinta )
					# avoid using underflow conversion
					snake_case							=					255
					snake_case							=					target - 1
					snake_case							=					255

					snake_case							=					Image.fromarray(A__ )
					return image, target







@dataclass
class lowerCamelCase   :
				snake_case_							     = field(
				    default='''segments/sidewalk-semantic'''				,				metadata={
				        '''help''': '''Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub).'''
				    }				,				)
				snake_case_							     = field(
				    default=_lowerCAmelCase				,				metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''}				)
				snake_case_							     = field(
				    default=0.15				,				metadata={'''help''': '''Percent to split off of train for validation.'''}				)
				snake_case_							     = field(
				    default=_lowerCAmelCase				,				metadata={
				        '''help''': (
				            '''For debugging purposes or quicker training, truncate the number of training examples to this '''
				            '''value if set.'''
				        )
				    }				,				)
				snake_case_							     = field(
				    default=_lowerCAmelCase				,				metadata={
				        '''help''': (
				            '''For debugging purposes or quicker training, truncate the number of evaluation examples to this '''
				            '''value if set.'''
				        )
				    }				,				)
				snake_case_							     = field(
				    default=_lowerCAmelCase				,				metadata={'''help''': '''Whether or not to reduce all labels by 1 and replace background by 255.'''}				,				)

				def 					_lowerCamelCase    (       self )    ->							List[str]:
					if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
						raise ValueError(
						    'You must specify either a dataset name from the hub or a train and/or validation directory.' )







@dataclass
class lowerCamelCase   :
				snake_case_							     = field(
				    default='''nvidia/mit-b0'''				,				metadata={'''help''': '''Path to pretrained model or model identifier from huggingface.co/models'''}				,				)
				snake_case_							     = field(
				    default=_lowerCAmelCase				,				metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''}				)
				snake_case_							     = field(
				    default=_lowerCAmelCase				,				metadata={'''help''': '''Where do you want to store the pretrained models downloaded from s3'''}				)
				snake_case_							     = field(
				    default='''main'''				,				metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''}				,				)
				snake_case_							     = field(default=_lowerCAmelCase				,				metadata={'''help''': '''Name or path of preprocessor config.'''}				)
				snake_case_							     = field(
				    default=_lowerCAmelCase				,				metadata={
				        '''help''': (
				            '''Will use the token generated when running `huggingface-cli login` (necessary to use this script '''
				            '''with private models).'''
				        )
				    }				,				)

def      __magic_name__							(			)      ->		Optional[Any]:
	snake_case							=					HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)				)
	if len(sys.argv				) == 2 and sys.argv[1].endswith('.json'				):
		# If we pass only one argument to the script and it's the path to a json file,
		# let's parse it to get our arguments.
		snake_case			,			snake_case			,			snake_case							=					parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]				)				)
	else:
		snake_case			,			snake_case			,			snake_case							=					parser.parse_args_into_dataclasses()

	# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
	# information sent is the one passed as arguments along with your Python/PyTorch versions.
	send_example_telemetry('run_semantic_segmentation'       , A       , A				)

	# Setup logging
	logging.basicConfig(
	    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'       , datefmt='%m/%d/%Y %H:%M:%S'       , handlers=[logging.StreamHandler(sys.stdout				)]       , )

	if training_args.should_log:
		# The default of training_args.log_level is passive, so we set log level at info here to have that default.
		transformers.utils.logging.set_verbosity_info()

	snake_case							=					training_args.get_process_log_level()
	logger.setLevel(A				)
	transformers.utils.logging.set_verbosity(A				)
	transformers.utils.logging.enable_default_handler()
	transformers.utils.logging.enable_explicit_format()

	# Log on each process the small summary:
	logger.warning(
	    F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
	    + F'''distributed training: {bool(training_args.local_rank != -1				)}, 16-bits training: {training_args.fpaa}'''				)
	logger.info(F'''Training/evaluation parameters {training_args}'''				)

	# Detecting last checkpoint.
	snake_case							=					None
	if os.path.isdir(training_args.output_dir				) and training_args.do_train and not training_args.overwrite_output_dir:
		snake_case							=					get_last_checkpoint(training_args.output_dir				)
		if last_checkpoint is None and len(os.listdir(training_args.output_dir				)				) > 0:
			raise ValueError(
			    F'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
			    'Use --overwrite_output_dir to overcome.'				)
		elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
			logger.info(
			    F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
			    'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'				)

    # Load dataset
    # In distributed training, the load_dataset function guarantees that only one local process can concurrently
    # download the dataset.
    # TODO support datasets from local folders
	snake_case							=					load_dataset(data_args.dataset_name       , cache_dir=model_args.cache_dir				)

	# Rename column names to standardized names (only "image" and "label" need to be present)
	if "pixel_values" in dataset["train"].column_names:
		snake_case							=					dataset.rename_columns({'pixel_values': 'image'}				)
	if "annotation" in dataset["train"].column_names:
		snake_case							=					dataset.rename_columns({'annotation': 'label'}				)

	# If we don't have a validation split, split off a percentage of train as validation.
	snake_case							=					None if 'validation' in dataset.keys() else data_args.train_val_split
	if isinstance(data_args.train_val_split       , A				) and data_args.train_val_split > 0.0:
		snake_case							=					dataset['train'].train_test_split(data_args.train_val_split				)
		snake_case							=					split['train']
		snake_case							=					split['test']

	# Prepare label mappings.
	# We'll include these in the model's config to get human readable labels in the Inference API.
	if data_args.dataset_name == "scene_parse_150":
		snake_case							=					'huggingface/label-files'
		snake_case							=					'ade20k-id2label.json'
	else:
		snake_case							=					data_args.dataset_name
		snake_case							=					'id2label.json'
	snake_case							=					json.load(open(hf_hub_download(A       , A       , repo_type='dataset'				)       , 'r'				)				)
	snake_case							=					{int(A				): v for k, v in idalabel.items()}
	snake_case							=					{v: str(A				) for k, v in idalabel.items()}

	# Load the mean IoU metric from the datasets package
	snake_case							=					evaluate.load('mean_iou'				)

	# Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
	# predictions and label_ids field) and has to return a dictionary string to float.
	@torch.no_grad()
	def compute_metrics(A				):
		snake_case			,			snake_case							=					eval_pred
		snake_case							=					torch.from_numpy(A				)
		# scale the logits to the size of the label
		snake_case							=					nn.functional.interpolate(
		    A       , size=labels.shape[-2:]       , mode='bilinear'       , align_corners=A       , ).argmax(dim=1				)

		snake_case							=					logits_tensor.detach().cpu().numpy()
		snake_case							=					metric.compute(
		    predictions=A       , references=A       , num_labels=len(A				)       , ignore_index=0       , reduce_labels=image_processor.do_reduce_labels       , )
		# add per category metrics as individual key-value pairs
		snake_case							=					metrics.pop('per_category_accuracy'				).tolist()
		snake_case							=					metrics.pop('per_category_iou'				).tolist()

		metrics.update({F'''accuracy_{idalabel[i]}''': v for i, v in enumerate(A				)}				)
		metrics.update({F'''iou_{idalabel[i]}''': v for i, v in enumerate(A				)}				)

		return metrics

	snake_case							=					AutoConfig.from_pretrained(
	    model_args.config_name or model_args.model_name_or_path       , labelaid=A       , idalabel=A       , cache_dir=model_args.cache_dir       , revision=model_args.model_revision       , use_auth_token=True if model_args.use_auth_token else None       , )
	snake_case							=					AutoModelForSemanticSegmentation.from_pretrained(
	    model_args.model_name_or_path       , from_tf=bool('.ckpt' in model_args.model_name_or_path				)       , config=A       , cache_dir=model_args.cache_dir       , revision=model_args.model_revision       , use_auth_token=True if model_args.use_auth_token else None       , )
	snake_case							=					AutoImageProcessor.from_pretrained(
	    model_args.image_processor_name or model_args.model_name_or_path       , cache_dir=model_args.cache_dir       , revision=model_args.model_revision       , use_auth_token=True if model_args.use_auth_token else None       , )

	# Define torchvision transforms to be applied to each image + target.
	# Not that straightforward in torchvision: https://github.com/pytorch/vision/issues/9
	# Currently based on official torchvision references: https://github.com/pytorch/vision/blob/main/references/segmentation/transforms.py
	if "shortest_edge" in image_processor.size:
		# We instead set the target size as (shortest_edge, shortest_edge) to here to ensure all images are batchable.
		snake_case							=					(image_processor.size['shortest_edge'], image_processor.size['shortest_edge'])
	else:
		snake_case							=					(image_processor.size['height'], image_processor.size['width'])
	snake_case							=					Compose(
	    [
	        ReduceLabels() if data_args.reduce_labels else Identity(),
	        RandomCrop(size=A				),
	        RandomHorizontalFlip(flip_prob=0.5				),
	        PILToTensor(),
	        ConvertImageDtype(torch.float				),
	        Normalize(mean=image_processor.image_mean       , std=image_processor.image_std				),
	    ]				)
	# Define torchvision transform to be applied to each image.
	# jitter = ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1)
	snake_case							=					Compose(
	    [
	        ReduceLabels() if data_args.reduce_labels else Identity(),
	        Resize(size=A				),
	        PILToTensor(),
	        ConvertImageDtype(torch.float				),
	        Normalize(mean=image_processor.image_mean       , std=image_processor.image_std				),
	    ]				)

	def preprocess_train(A				):
		snake_case							=					[]
		snake_case							=					[]
		for image, target in zip(example_batch['image']       , example_batch['label']				):
			snake_case			,			snake_case							=					train_transforms(image.convert('RGB'				)       , A				)
			pixel_values.append(A				)
			labels.append(A				)

		snake_case							=					{}
		snake_case							=					torch.stack(A				)
		snake_case							=					torch.stack(A				)

		return encoding

	def preprocess_val(A				):
		snake_case							=					[]
		snake_case							=					[]
		for image, target in zip(example_batch['image']       , example_batch['label']				):
			snake_case			,			snake_case							=					val_transforms(image.convert('RGB'				)       , A				)
			pixel_values.append(A				)
			labels.append(A				)

		snake_case							=					{}
		snake_case							=					torch.stack(A				)
		snake_case							=					torch.stack(A				)

		return encoding

	if training_args.do_train:
		if "train" not in dataset:
			raise ValueError('--do_train requires a train dataset'				)
		if data_args.max_train_samples is not None:
			snake_case							=					(
			    dataset['train'].shuffle(seed=training_args.seed				).select(range(data_args.max_train_samples				)				)
			)
		# Set the training transforms
		dataset["train"].set_transform(A				)

	if training_args.do_eval:
		if "validation" not in dataset:
			raise ValueError('--do_eval requires a validation dataset'				)
		if data_args.max_eval_samples is not None:
			snake_case							=					(
			    dataset['validation'].shuffle(seed=training_args.seed				).select(range(data_args.max_eval_samples				)				)
			)
		# Set the validation transforms
		dataset["validation"].set_transform(A				)

	# Initalize our trainer
	snake_case							=					Trainer(
	    model=A       , args=A       , train_dataset=dataset['train'] if training_args.do_train else None       , eval_dataset=dataset['validation'] if training_args.do_eval else None       , compute_metrics=A       , tokenizer=A       , data_collator=A       , )

	# Training
	if training_args.do_train:
		snake_case							=					None
		if training_args.resume_from_checkpoint is not None:
			snake_case							=					training_args.resume_from_checkpoint
		elif last_checkpoint is not None:
			snake_case							=					last_checkpoint
		snake_case							=					trainer.train(resume_from_checkpoint=A				)
		trainer.save_model()
		trainer.log_metrics('train'       , train_result.metrics				)
		trainer.save_metrics('train'       , train_result.metrics				)
		trainer.save_state()

	# Evaluation
	if training_args.do_eval:
		snake_case							=					trainer.evaluate()
		trainer.log_metrics('eval'       , A				)
		trainer.save_metrics('eval'       , A				)

	# Write model card and (optionally) push to hub
	snake_case							=					{
	    'finetuned_from': model_args.model_name_or_path,
	    'dataset': data_args.dataset_name,
	    'tags': ['image-segmentation', 'vision'],
	}
	if training_args.push_to_hub:
		trainer.push_to_hub(**A				)
	else:
		trainer.create_model_card(**A				)


if __name__ == "__main__":
						main()











from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    convert_to_rgb,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    OPENAI_CLIP_MEAN,
    OPENAI_CLIP_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


__SCREAMING_SNAKE_CASE     : Dict      =logging.get_logger(__name__)


if is_vision_available():
      import PIL






class       A      (		_lowerCAmelCase		):
     """simple docstring"""

     _snake_case:						Any  =["pixel_values"]




     def __init__(     self	: Union[str, Any]						,	A__	: bool = True						,	A__	: Dict[str, int] = None						,	A__	: PILImageResampling = PILImageResampling.BICUBIC						,	A__	: bool = True						,	A__	: Dict[str, int] = None						,	A__	: bool = True						,	A__	: Union[int, float] = 1 / 2_5_5						,	A__	: bool = True						,	A__	: Optional[Union[float, List[float]]] = None						,	A__	: Optional[Union[float, List[float]]] = None						,	A__	: bool = True						,	**A__	: Optional[int]						,	)					->							None:
           super().__init__(**A__      )
           lowerCamelCase__   	=					size if size is not None else {'shortest_edge': 2_2_4}
           lowerCamelCase__   	=					get_size_dict(A__						,	default_to_square=A__      )
           lowerCamelCase__   	=					crop_size if crop_size is not None else {'height': 2_2_4, 'width': 2_2_4}
           lowerCamelCase__   	=					get_size_dict(A__      )

           lowerCamelCase__   	=					do_resize
           lowerCamelCase__   	=					size
           lowerCamelCase__   	=					resample
           lowerCamelCase__   	=					do_center_crop
           lowerCamelCase__   	=					crop_size
           lowerCamelCase__   	=					do_rescale
           lowerCamelCase__   	=					rescale_factor
           lowerCamelCase__   	=					do_normalize
           lowerCamelCase__   	=					image_mean if image_mean is not None else OPENAI_CLIP_MEAN
           lowerCamelCase__   	=					image_std if image_std is not None else OPENAI_CLIP_STD
           lowerCamelCase__   	=					do_convert_rgb




     def 			__snake_case (     self	: Union[str, Any]						,	A__	: np.ndarray						,	A__	: Dict[str, int]						,	A__	: PILImageResampling = PILImageResampling.BICUBIC						,	A__	: Optional[Union[str, ChannelDimension]] = None						,	**A__	: Optional[int]						,	)					->							np.ndarray:
           lowerCamelCase__   	=					get_size_dict(A__						,	default_to_square=A__      )
           lowerCamelCase__   	=					get_resize_output_image_size(
               A__						,	size=(size['height'], size['width'])						,	default_to_square=A__      )
           return resize(A__						,	size=A__						,	resample=A__						,	data_format=A__						,	**A__      )




     def 			__snake_case (     self	: int						,	A__	: np.ndarray						,	A__	: Dict[str, int]						,	A__	: Optional[Union[str, ChannelDimension]] = None						,	**A__	: List[Any]						,	)					->							np.ndarray:
           lowerCamelCase__   	=					get_size_dict(A__      )
           return center_crop(A__						,	size=(size['height'], size['width'])						,	data_format=A__						,	**A__      )




     def 			__snake_case (     self	: Dict						,	A__	: np.ndarray						,	A__	: Union[int, float]						,	A__	: Optional[Union[str, ChannelDimension]] = None						,	**A__	: List[Any]						,	)					->							Tuple:
           return rescale(A__						,	scale=A__						,	data_format=A__						,	**A__      )




     def 			__snake_case (     self	: int						,	A__	: np.ndarray						,	A__	: Union[float, List[float]]						,	A__	: Union[float, List[float]]						,	A__	: Optional[Union[str, ChannelDimension]] = None						,	**A__	: Tuple						,	)					->							np.ndarray:
           return normalize(A__						,	mean=A__						,	std=A__						,	data_format=A__						,	**A__      )




     def 			__snake_case (     self	: Tuple						,	A__	: ImageInput						,	A__	: bool = None						,	A__	: Dict[str, int] = None						,	A__	: PILImageResampling = None						,	A__	: bool = None						,	A__	: int = None						,	A__	: bool = None						,	A__	: float = None						,	A__	: bool = None						,	A__	: Optional[Union[float, List[float]]] = None						,	A__	: Optional[Union[float, List[float]]] = None						,	A__	: bool = None						,	A__	: Optional[Union[str, TensorType]] = None						,	A__	: Optional[ChannelDimension] = ChannelDimension.FIRST						,	**A__	: List[str]						,	)					->							PIL.Image.Image:
           lowerCamelCase__   	=					do_resize if do_resize is not None else self.do_resize
           lowerCamelCase__   	=					size if size is not None else self.size
           lowerCamelCase__   	=					get_size_dict(A__						,	default_to_square=A__      )
           lowerCamelCase__   	=					resample if resample is not None else self.resample
           lowerCamelCase__   	=					do_center_crop if do_center_crop is not None else self.do_center_crop
           lowerCamelCase__   	=					crop_size if crop_size is not None else self.crop_size
           lowerCamelCase__   	=					get_size_dict(A__      )
           lowerCamelCase__   	=					do_rescale if do_rescale is not None else self.do_rescale
           lowerCamelCase__   	=					rescale_factor if rescale_factor is not None else self.rescale_factor
           lowerCamelCase__   	=					do_normalize if do_normalize is not None else self.do_normalize
           lowerCamelCase__   	=					image_mean if image_mean is not None else self.image_mean
           lowerCamelCase__   	=					image_std if image_std is not None else self.image_std
           lowerCamelCase__   	=					do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb

           lowerCamelCase__   	=					make_list_of_images(A__      )

           if not valid_images(A__      ):
                 raise ValueError(
                     'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, '
                     'torch.Tensor, tf.Tensor or jax.ndarray.'      )

           if do_resize and size is None:
                 raise ValueError('Size must be specified if do_resize is True.'      )

           if do_center_crop and crop_size is None:
                 raise ValueError('Crop size must be specified if do_center_crop is True.'      )

           if do_rescale and rescale_factor is None:
                 raise ValueError('Rescale factor must be specified if do_rescale is True.'      )

           if do_normalize and (image_mean is None or image_std is None):
                 raise ValueError('Image mean and std must be specified if do_normalize is True.'      )

           # PIL RGBA images are converted to RGB
           if do_convert_rgb:
                 lowerCamelCase__   	=					[convert_to_rgb(A__      ) for image in images]

           # All transformations expect numpy arrays.
           lowerCamelCase__   	=					[to_numpy_array(A__      ) for image in images]

           if do_resize:
                 lowerCamelCase__   	=					[self.resize(image=A__						,	size=A__						,	resample=A__      ) for image in images]

           if do_center_crop:
                 lowerCamelCase__   	=					[self.center_crop(image=A__						,	size=A__      ) for image in images]

           if do_rescale:
                 lowerCamelCase__   	=					[self.rescale(image=A__						,	scale=A__      ) for image in images]

           if do_normalize:
                 lowerCamelCase__   	=					[self.normalize(image=A__						,	mean=A__						,	std=A__      ) for image in images]

           lowerCamelCase__   	=					[to_channel_dimension_format(A__						,	A__      ) for image in images]

           lowerCamelCase__   	=					{'pixel_values': images}
           return BatchFeature(data=A__						,	tensor_type=A__      )