codingutf8 2022 the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache orglicenseslicense2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license image processor class for glpn from typing import list optional union import numpy as np import pil image from imageprocessingutils import baseimageprocessor batchfeature from imagetransforms import resize tochanneldimensionformat from imageutils import channeldimension pilimageresampling getimagesize inferchanneldimensionformat isscaledimage makelistofimages tonumpyarray validimages from utils import tensortype logging logger logging getloggername class glpnimageprocessorbaseimageprocessor r constructs a glpn image processor args doresize bool optional defaults to true whether to resize the image s height width dimensions rounding them down to the closest multiple of sizedivisor can be overridden by doresize in preprocess sizedivisor int optional defaults to 32 when doresize is true images are resized so their height and width are rounded down to the closest multiple of sizedivisor can be overridden by sizedivisor in preprocess resample pil image resampling filter optional defaults to resampling bilinear resampling filter to use if resizing the image can be overridden by resample in preprocess dorescale bool optional defaults to true whether or not to apply the scaling factor to make pixel values floats between 0 and 1 can be overridden by dorescale in preprocess resize the image rounding the height width dimensions down to the closest multiple of sizedivisor if the image is of dimension 3 260 170 and sizedivisor is 32 the image will be resized to 3 256 160 args image np ndarray the image to resize sizedivisor int the image is resized so its height and width are rounded down to the closest multiple of sizedivisor resample pil image resampling filter to use when resizing the image e g pilimageresampling bilinear dataformat channeldimension or str optional the channel dimension format for the output image if none the channel dimension format of the input image is used can be one of channeldimension first image in numchannels height width format channeldimension last image in height width numchannels format inputdataformat channeldimension or str optional the channel dimension format of the input image if not set the channel dimension format is inferred from the input image can be one of channelsfirst or channeldimension first image in numchannels height width format channelslast or channeldimension last image in height width numchannels format returns np ndarray the resized image rounds the height and width down to the closest multiple of sizedivisor preprocess the given images args images pil image image or tensortype or listnp ndarray or listtensortype images to preprocess expects a single or batch of images with pixel values ranging from 0 to 255 if passing in images with pixel values between 0 and 1 set donormalizefalse doresize bool optional defaults to self doresize whether to resize the input such that the height width dimensions are a multiple of sizedivisor sizedivisor int optional defaults to self sizedivisor when doresize is true images are resized so their height and width are rounded down to the closest multiple of sizedivisor resample pil image resampling filter optional defaults to self resample pil image resampling filter to use if resizing the image e g pilimageresampling bilinear only has an effect if doresize is set to true dorescale bool optional defaults to self dorescale whether or not to apply the scaling factor to make pixel values floats between 0 and 1 returntensors str or tensortype optional the type of tensors to return can be one of none return a list of np ndarray tensortype tensorflow or tf return a batch of type tf tensor tensortype pytorch or pt return a batch of type torch tensor tensortype numpy or np return a batch of type np ndarray tensortype jax or jax return a batch of type jax numpy ndarray dataformat channeldimension or str optional defaults to channeldimension first the channel dimension format for the output image can be one of channeldimension first image in numchannels height width format channeldimension last image in height width numchannels format inputdataformat channeldimension or str optional the channel dimension format for the input image if unset the channel dimension format is inferred from the input image can be one of channelsfirst or channeldimension first image in numchannels height width format channelslast or channeldimension last image in height width numchannels format none or channeldimension none image in height width format all transformations expect numpy arrays we assume that all images have the same channel dimension format coding utf 8 2022 the huggingface inc team licensed under the apache license version 2 0 the license you may not use this file except in compliance with the license you may obtain a copy of the license at http www apache org licenses license 2 0 unless required by applicable law or agreed to in writing software distributed under the license is distributed on an as is basis without warranties or conditions of any kind either express or implied see the license for the specific language governing permissions and limitations under the license image processor class for glpn constructs a glpn image processor args do_resize bool optional defaults to true whether to resize the image s height width dimensions rounding them down to the closest multiple of size_divisor can be overridden by do_resize in preprocess size_divisor int optional defaults to 32 when do_resize is true images are resized so their height and width are rounded down to the closest multiple of size_divisor can be overridden by size_divisor in preprocess resample pil image resampling filter optional defaults to resampling bilinear resampling filter to use if resizing the image can be overridden by resample in preprocess do_rescale bool optional defaults to true whether or not to apply the scaling factor to make pixel values floats between 0 and 1 can be overridden by do_rescale in preprocess resize the image rounding the height width dimensions down to the closest multiple of size_divisor if the image is of dimension 3 260 170 and size_divisor is 32 the image will be resized to 3 256 160 args image np ndarray the image to resize size_divisor int the image is resized so its height and width are rounded down to the closest multiple of size_divisor resample pil image resampling filter to use when resizing the image e g pilimageresampling bilinear data_format channeldimension or str optional the channel dimension format for the output image if none the channel dimension format of the input image is used can be one of channeldimension first image in num_channels height width format channeldimension last image in height width num_channels format input_data_format channeldimension or str optional the channel dimension format of the input image if not set the channel dimension format is inferred from the input image can be one of channels_first or channeldimension first image in num_channels height width format channels_last or channeldimension last image in height width num_channels format returns np ndarray the resized image rounds the height and width down to the closest multiple of size_divisor preprocess the given images args images pil image image or tensortype or list np ndarray or list tensortype images to preprocess expects a single or batch of images with pixel values ranging from 0 to 255 if passing in images with pixel values between 0 and 1 set do_normalize false do_resize bool optional defaults to self do_resize whether to resize the input such that the height width dimensions are a multiple of size_divisor size_divisor int optional defaults to self size_divisor when do_resize is true images are resized so their height and width are rounded down to the closest multiple of size_divisor resample pil image resampling filter optional defaults to self resample pil image resampling filter to use if resizing the image e g pilimageresampling bilinear only has an effect if do_resize is set to true do_rescale bool optional defaults to self do_rescale whether or not to apply the scaling factor to make pixel values floats between 0 and 1 return_tensors str or tensortype optional the type of tensors to return can be one of none return a list of np ndarray tensortype tensorflow or tf return a batch of type tf tensor tensortype pytorch or pt return a batch of type torch tensor tensortype numpy or np return a batch of type np ndarray tensortype jax or jax return a batch of type jax numpy ndarray data_format channeldimension or str optional defaults to channeldimension first the channel dimension format for the output image can be one of channeldimension first image in num_channels height width format channeldimension last image in height width num_channels format input_data_format channeldimension or str optional the channel dimension format for the input image if unset the channel dimension format is inferred from the input image can be one of channels_first or channeldimension first image in num_channels height width format channels_last or channeldimension last image in height width num_channels format none or channeldimension none image in height width format all transformations expect numpy arrays we assume that all images have the same channel dimension format
from typing import List, Optional, Union

import numpy as np
import PIL.Image

from ...image_processing_utils import BaseImageProcessor, BatchFeature
from ...image_transforms import resize, to_channel_dimension_format
from ...image_utils import (
    ChannelDimension,
    PILImageResampling,
    get_image_size,
    infer_channel_dimension_format,
    is_scaled_image,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, logging


logger = logging.get_logger(__name__)


class GLPNImageProcessor(BaseImageProcessor):
    r

    model_input_names = ["pixel_values"]

    def __init__(
        self,
        do_resize: bool = True,
        size_divisor: int = 32,
        resample=PILImageResampling.BILINEAR,
        do_rescale: bool = True,
        **kwargs,
    ) -> None:
        self.do_resize = do_resize
        self.do_rescale = do_rescale
        self.size_divisor = size_divisor
        self.resample = resample
        super().__init__(**kwargs)

    def resize(
        self,
        image: np.ndarray,
        size_divisor: int,
        resample: PILImageResampling = PILImageResampling.BILINEAR,
        data_format: Optional[ChannelDimension] = None,
        input_data_format: Optional[Union[str, ChannelDimension]] = None,
        **kwargs,
    ) -> np.ndarray:
        
        height, width = get_image_size(image, channel_dim=input_data_format)
        
        new_h = height // size_divisor * size_divisor
        new_w = width // size_divisor * size_divisor
        image = resize(
            image,
            (new_h, new_w),
            resample=resample,
            data_format=data_format,
            input_data_format=input_data_format,
            **kwargs,
        )
        return image

    def preprocess(
        self,
        images: Union["PIL.Image.Image", TensorType, List["PIL.Image.Image"], List[TensorType]],
        do_resize: Optional[bool] = None,
        size_divisor: Optional[int] = None,
        resample=None,
        do_rescale: Optional[bool] = None,
        return_tensors: Optional[Union[TensorType, str]] = None,
        data_format: ChannelDimension = ChannelDimension.FIRST,
        input_data_format: Optional[Union[str, ChannelDimension]] = None,
        **kwargs,
    ) -> BatchFeature:
        
        do_resize = do_resize if do_resize is not None else self.do_resize
        do_rescale = do_rescale if do_rescale is not None else self.do_rescale
        size_divisor = size_divisor if size_divisor is not None else self.size_divisor
        resample = resample if resample is not None else self.resample

        if do_resize and size_divisor is None:
            raise ValueError("size_divisor is required for resizing")

        images = make_list_of_images(images)

        if not valid_images(images):
            raise ValueError("Invalid image(s)")

        
        images = [to_numpy_array(img) for img in images]

        if is_scaled_image(images[0]) and do_rescale:
            logger.warning_once(
                "It looks like you are trying to rescale already rescaled images. If the input"
                " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
            )

        if input_data_format is None:
            
            input_data_format = infer_channel_dimension_format(images[0])

        if do_resize:
            images = [
                self.resize(image, size_divisor=size_divisor, resample=resample, input_data_format=input_data_format)
                for image in images
            ]

        if do_rescale:
            images = [self.rescale(image, scale=1 / 255, input_data_format=input_data_format) for image in images]

        images = [
            to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
        ]

        data = {"pixel_values": images}
        return BatchFeature(data=data, tensor_type=return_tensors)