





"""simple docstring"""
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_video_inputs


if is_torch_available():
  import torch

if is_vision_available():
  from PIL import Image

  from transformers import VivitImageProcessor






class 					_SCREAMING_SNAKE_CASE(   unittest.TestCase  ):




       def __init__(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__=7		,SCREAMING_SNAKE_CASE__=3		,SCREAMING_SNAKE_CASE__=10		,SCREAMING_SNAKE_CASE__=18		,SCREAMING_SNAKE_CASE__=30		,SCREAMING_SNAKE_CASE__=4_00		,SCREAMING_SNAKE_CASE__=True		,SCREAMING_SNAKE_CASE__=None		,SCREAMING_SNAKE_CASE__=True		,SCREAMING_SNAKE_CASE__=[0.5, 0.5, 0.5]		,SCREAMING_SNAKE_CASE__=[0.5, 0.5, 0.5]		,SCREAMING_SNAKE_CASE__=None		,)			->      Union[str, Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :str						=  size if size is not None else {'''shortest_edge''': 18}
             __SCREAMING_SNAKE_CASE   :int						=  crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}

             __SCREAMING_SNAKE_CASE   :Tuple						=  parent
             __SCREAMING_SNAKE_CASE   :str						=  batch_size
             __SCREAMING_SNAKE_CASE   :Dict						=  num_channels
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  num_frames
             __SCREAMING_SNAKE_CASE   :List[Any]						=  image_size
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  min_resolution
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  max_resolution
             __SCREAMING_SNAKE_CASE   :Any						=  do_resize
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  size
             __SCREAMING_SNAKE_CASE   :List[str]						=  do_normalize
             __SCREAMING_SNAKE_CASE   :int						=  image_mean
             __SCREAMING_SNAKE_CASE   :Any						=  image_std
             __SCREAMING_SNAKE_CASE   :int						=  crop_size




       def     _UpperCamelCase     (						self							)			->      Dict:





             """simple docstring"""






             return {
                 "image_mean": self.image_mean,
                 "image_std": self.image_std,
                 "do_normalize": self.do_normalize,
                 "do_resize": self.do_resize,
                 "size": self.size,
                 "crop_size": self.crop_size,
             }






@require_torch
@require_vision
class 					_SCREAMING_SNAKE_CASE(   A__    ,	unittest.TestCase  ):
       SCREAMING_SNAKE_CASE_   :      Any							=  VivitImageProcessor if is_vision_available() else None




       def     _UpperCamelCase     (						self							)			->      Union[str, Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Any						=  VivitImageProcessingTester(self							)




       @property
       def     _UpperCamelCase     (						self							)			->      List[Any]:





             """simple docstring"""






             return self.image_processor_tester.prepare_image_processor_dict()




       def     _UpperCamelCase     (						self							)			->      List[Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Tuple						=  self.image_processing_class(**self.image_processor_dict							)
             self.assertTrue(hasattr(_a		,'''image_mean'''							)							)
             self.assertTrue(hasattr(_a		,'''image_std'''							)							)
             self.assertTrue(hasattr(_a		,'''do_normalize'''							)							)
             self.assertTrue(hasattr(_a		,'''do_resize'''							)							)
             self.assertTrue(hasattr(_a		,'''do_center_crop'''							)							)
             self.assertTrue(hasattr(_a		,'''size'''							)							)




       def     _UpperCamelCase     (						self							)			->      Any:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Dict						=  self.image_processing_class.from_dict(self.image_processor_dict							)
             self.assertEqual(image_processor.size		,{'''shortest_edge''': 18}							)
             self.assertEqual(image_processor.crop_size		,{'''height''': 18, '''width''': 18}							)

             __SCREAMING_SNAKE_CASE   :List[str]						=  self.image_processing_class.from_dict(self.image_processor_dict		,size=42		,crop_size=84							)
             self.assertEqual(image_processor.size		,{'''shortest_edge''': 42}							)
             self.assertEqual(image_processor.crop_size		,{'''height''': 84, '''width''': 84}							)




       def     _UpperCamelCase     (						self							)			->      str:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Dict						=  self.image_processing_class(**self.image_processor_dict							)
             # create random PIL videos
             __SCREAMING_SNAKE_CASE   :List[str]						=  prepare_video_inputs(self.image_processor_tester		,equal_resolution=_a							)
             for video in video_inputs:
                   self.assertIsInstance(_a		,_a							)
                   self.assertIsInstance(video[0]		,Image.Image							)

             # Test not batched input
             __SCREAMING_SNAKE_CASE   :Optional[int]						=  image_processing(video_inputs[0]		,return_tensors='''pt'''							).pixel_values
             self.assertEqual(
                 encoded_videos.shape		,(
                     1,
                     self.image_processor_tester.num_frames,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size['''height'''],
                     self.image_processor_tester.crop_size['''width'''],
                 )		,)

             # Test batched
             __SCREAMING_SNAKE_CASE   :Any						=  image_processing(_a		,return_tensors='''pt'''							).pixel_values
             self.assertEqual(
                 encoded_videos.shape		,(
                     self.image_processor_tester.batch_size,
                     self.image_processor_tester.num_frames,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size['''height'''],
                     self.image_processor_tester.crop_size['''width'''],
                 )		,)




       def     _UpperCamelCase     (						self							)			->      List[Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Optional[int]						=  self.image_processing_class(**self.image_processor_dict							)
             # create random numpy tensors
             __SCREAMING_SNAKE_CASE   :List[Any]						=  prepare_video_inputs(self.image_processor_tester		,equal_resolution=_a		,numpify=_a							)
             for video in video_inputs:
                   self.assertIsInstance(_a		,_a							)
                   self.assertIsInstance(video[0]		,np.ndarray							)

             # Test not batched input
             __SCREAMING_SNAKE_CASE   :int						=  image_processing(video_inputs[0]		,return_tensors='''pt'''							).pixel_values
             self.assertEqual(
                 encoded_videos.shape		,(
                     1,
                     self.image_processor_tester.num_frames,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size['''height'''],
                     self.image_processor_tester.crop_size['''width'''],
                 )		,)

             # Test batched
             __SCREAMING_SNAKE_CASE   :Any						=  image_processing(_a		,return_tensors='''pt'''							).pixel_values
             self.assertEqual(
                 encoded_videos.shape		,(
                     self.image_processor_tester.batch_size,
                     self.image_processor_tester.num_frames,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size['''height'''],
                     self.image_processor_tester.crop_size['''width'''],
                 )		,)




       def     _UpperCamelCase     (						self							)			->      Any:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE   :Optional[int]						=  self.image_processing_class(**self.image_processor_dict							)
             # create random PyTorch tensors
             __SCREAMING_SNAKE_CASE   :str						=  prepare_video_inputs(self.image_processor_tester		,equal_resolution=_a		,torchify=_a							)
             for video in video_inputs:
                   self.assertIsInstance(_a		,_a							)
                   self.assertIsInstance(video[0]		,torch.Tensor							)

             # Test not batched input
             __SCREAMING_SNAKE_CASE   :Optional[Any]						=  image_processing(video_inputs[0]		,return_tensors='''pt'''							).pixel_values
             self.assertEqual(
                 encoded_videos.shape		,(
                     1,
                     self.image_processor_tester.num_frames,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size['''height'''],
                     self.image_processor_tester.crop_size['''width'''],
                 )		,)

             # Test batched
             __SCREAMING_SNAKE_CASE   :Union[str, Any]						=  image_processing(_a		,return_tensors='''pt'''							).pixel_values
             self.assertEqual(
                 encoded_videos.shape		,(
                     self.image_processor_tester.batch_size,
                     self.image_processor_tester.num_frames,
                     self.image_processor_tester.num_channels,
                     self.image_processor_tester.crop_size['''height'''],
                     self.image_processor_tester.crop_size['''width'''],
                 )		,)


'''simple docstring'''
import numpy as np
from PIL import Image


def        _lowerCAmelCase					(						_UpperCamelCase						:     np.ndarray							, _UpperCamelCase						:     int							, _UpperCamelCase						:     int				)      ->			np.ndarray:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							    =np.array(_UpperCamelCase				)
     if arr.shape[0] != arr.shape[1]:
          raise ValueError('The input array is not a square matrix'				)
     _SCREAMING_SNAKE_CASE							    =0
     _SCREAMING_SNAKE_CASE							    =0
     _SCREAMING_SNAKE_CASE							    =0
     _SCREAMING_SNAKE_CASE							    =0

     # compute the shape of the output matrix
     _SCREAMING_SNAKE_CASE							    =(arr.shape[0] - size) // stride + 1
     # initialize the output matrix with zeros of shape maxpool_shape
     _SCREAMING_SNAKE_CASE							    =np.zeros((maxpool_shape, maxpool_shape)				)

     while i < arr.shape[0]:
          if i + size > arr.shape[0]:
               # if the end of the matrix is reached, break
               break
          while j < arr.shape[1]:
               # if the end of the matrix is reached, break
               if j + size > arr.shape[1]:
                    break
               # compute the maximum of the pooling matrix
               _SCREAMING_SNAKE_CASE							    =np.max(arr[i : i + size, j : j + size]				)
               # shift the pooling matrix by stride of column pixels
               j += stride
               mat_j += 1

          # shift the pooling matrix by stride of row pixels
          i += stride
          mat_i += 1

          # reset the column index to 0
          _SCREAMING_SNAKE_CASE							    =0
          _SCREAMING_SNAKE_CASE							    =0

     return updated_arr


def        _lowerCAmelCase					(						_UpperCamelCase						:     np.ndarray							, _UpperCamelCase						:     int							, _UpperCamelCase						:     int				)      ->			np.ndarray:
     """simple docstring"""




     _SCREAMING_SNAKE_CASE							    =np.array(_UpperCamelCase				)
     if arr.shape[0] != arr.shape[1]:
          raise ValueError('The input array is not a square matrix'				)
     _SCREAMING_SNAKE_CASE							    =0
     _SCREAMING_SNAKE_CASE							    =0
     _SCREAMING_SNAKE_CASE							    =0
     _SCREAMING_SNAKE_CASE							    =0

     # compute the shape of the output matrix
     _SCREAMING_SNAKE_CASE							    =(arr.shape[0] - size) // stride + 1
     # initialize the output matrix with zeros of shape avgpool_shape
     _SCREAMING_SNAKE_CASE							    =np.zeros((avgpool_shape, avgpool_shape)				)

     while i < arr.shape[0]:
          # if the end of the matrix is reached, break
          if i + size > arr.shape[0]:
               break
          while j < arr.shape[1]:
               # if the end of the matrix is reached, break
               if j + size > arr.shape[1]:
                    break
               # compute the average of the pooling matrix
               _SCREAMING_SNAKE_CASE							    =int(np.average(arr[i : i + size, j : j + size]				)				)
               # shift the pooling matrix by stride of column pixels
               j += stride
               mat_j += 1

          # shift the pooling matrix by stride of row pixels
          i += stride
          mat_i += 1
          # reset the column index to 0
          _SCREAMING_SNAKE_CASE							    =0
          _SCREAMING_SNAKE_CASE							    =0

     return updated_arr


# Main Function
if __name__ == "__main__":
     from doctest import testmod

     testmod(name="avgpooling", verbose=True)

     # Loading the image
     lowerCamelCase :      Optional[Any]					 =     Image.open("path_to_image")

     # Converting the image to numpy array and maxpooling, displaying the result
     # Ensure that the image is a square matrix

     Image.fromarray(maxpooling(np.array(image), size=3, stride=2)).show()

     # Converting the image to numpy array and averagepooling, displaying the result
     # Ensure that the image is a square matrix

     Image.fromarray(avgpooling(np.array(image), size=3, stride=2)).show()
