



"""simple docstring"""




from typing import Dict, Optional

import numpy as np

import datasets


_lowerCAmelCase    : List[Any]							=							"\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,\nthe mean IoU of the image is calculated by taking the IoU of each class and averaging them.\n"

_lowerCAmelCase    : str							=							"\nArgs:\n    predictions (`List[ndarray]`):\n        List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n    references (`List[ndarray]`):\n        List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n    num_labels (`int`):\n        Number of classes (categories).\n    ignore_index (`int`):\n        Index that will be ignored during evaluation.\n    nan_to_num (`int`, *optional*):\n        If specified, NaN values will be replaced by the number defined by the user.\n    label_map (`dict`, *optional*):\n        If specified, dictionary mapping old label indices to new label indices.\n    reduce_labels (`bool`, *optional*, defaults to `False`):\n        Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,\n        and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.\n\nReturns:\n    `Dict[str, float | ndarray]` comprising various elements:\n    - *mean_iou* (`float`):\n        Mean Intersection-over-Union (IoU averaged over all categories).\n    - *mean_accuracy* (`float`):\n        Mean accuracy (averaged over all categories).\n    - *overall_accuracy* (`float`):\n        Overall accuracy on all images.\n    - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):\n        Per category accuracy.\n    - *per_category_iou* (`ndarray` of shape `(num_labels,)`):\n        Per category IoU.\n\nExamples:\n\n    >>> import numpy as np\n\n    >>> mean_iou = datasets.load_metric(\"mean_iou\")\n\n    >>> # suppose one has 3 different segmentation maps predicted\n    >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])\n    >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])\n\n    >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])\n    >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])\n\n    >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])\n    >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])\n\n    >>> predicted = [predicted_1, predicted_2, predicted_3]\n    >>> ground_truth = [actual_1, actual_2, actual_3]\n\n    >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)\n    >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n    {'mean_iou': 0.47750000000000004, 'mean_accuracy': 0.5916666666666666, 'overall_accuracy': 0.5263157894736842, 'per_category_iou': array([0.   , 0.   , 0.375, 0.4  , 0.5  , 0.   , 0.5  , 1.   , 1.   , 1.   ]), 'per_category_accuracy': array([0.        , 0.        , 0.75      , 0.66666667, 1.        , 0.        , 0.5       , 1.        , 1.        , 1.        ])}\n"

_lowerCAmelCase    : Optional[Any]							=							"\\n@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,\nauthor = {{MMSegmentation Contributors}},\nlicense = {Apache-2.0},\nmonth = {7},\ntitle = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},\nurl = {https://github.com/open-mmlab/mmsegmentation},\nyear = {2020}\n}"

def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						Union[str, Any]						,  SCREAMING_SNAKE_CASE__     :						Union[str, Any]						,  SCREAMING_SNAKE_CASE__     :						List[str]						,  SCREAMING_SNAKE_CASE__     :						bool						,  SCREAMING_SNAKE_CASE__     :						Optional[Dict[int, int]] = None						,  SCREAMING_SNAKE_CASE__     :						bool = False						,  )  ->       Union[str, Any]:





     '''simple docstring'''

     if label_map is not None:
          for old_id, new_id in label_map.items():
               _UpperCAmelCase      :     str        =   new_id

    # turn into Numpy arrays
     _UpperCAmelCase      :     List[str]        =   np.array(lowerCAmelCase__    )
     _UpperCAmelCase      :     int        =   np.array(lowerCAmelCase__    )

     if reduce_labels:
          _UpperCAmelCase      :     Any        =   255
          _UpperCAmelCase      :     str        =   label - 1
          _UpperCAmelCase      :     List[Any]        =   255

     _UpperCAmelCase      :     List[Any]        =   label != ignore_index
     _UpperCAmelCase      :     str        =   np.not_equal(lowerCAmelCase__						,  lowerCAmelCase__    )
     _UpperCAmelCase      :     Optional[int]        =   pred_label[mask]
     _UpperCAmelCase      :     str        =   np.array(lowerCAmelCase__    )[mask]

     _UpperCAmelCase      :     Tuple        =   pred_label[pred_label == label]

     _UpperCAmelCase      :     Optional[int]        =   np.histogram(lowerCAmelCase__						,  bins=lowerCAmelCase__						,  range=(0, num_labels - 1)    )[0]
     _UpperCAmelCase      :     Dict        =   np.histogram(lowerCAmelCase__						,  bins=lowerCAmelCase__						,  range=(0, num_labels - 1)    )[0]
     _UpperCAmelCase      :     List[str]        =   np.histogram(lowerCAmelCase__						,  bins=lowerCAmelCase__						,  range=(0, num_labels - 1)    )[0]

     _UpperCAmelCase      :     Optional[int]        =   area_pred_label + area_label - area_intersect

     return area_intersect, area_union, area_pred_label, area_label

def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						Any						,  SCREAMING_SNAKE_CASE__     :						Any						,  SCREAMING_SNAKE_CASE__     :						int						,  SCREAMING_SNAKE_CASE__     :						bool						,  SCREAMING_SNAKE_CASE__     :						Optional[Dict[int, int]] = None						,  SCREAMING_SNAKE_CASE__     :						bool = False						,  )  ->       Dict:





     '''simple docstring'''

     _UpperCAmelCase      :     List[Any]        =   np.zeros((num_labels,)						,  dtype=np.floataa    )
     _UpperCAmelCase      :     Tuple        =   np.zeros((num_labels,)						,  dtype=np.floataa    )
     _UpperCAmelCase      :     Optional[Any]        =   np.zeros((num_labels,)						,  dtype=np.floataa    )
     _UpperCAmelCase      :     List[Any]        =   np.zeros((num_labels,)						,  dtype=np.floataa    )
     for result, gt_seg_map in zip(lowerCAmelCase__						,  lowerCAmelCase__    ):
          _UpperCAmelCase    ,	_UpperCAmelCase    ,	_UpperCAmelCase    ,	_UpperCAmelCase      :     Dict        =   intersect_and_union(
              lowerCAmelCase__						,  lowerCAmelCase__						,  lowerCAmelCase__						,  lowerCAmelCase__						,  lowerCAmelCase__						,  lowerCAmelCase__    )
          total_area_intersect += area_intersect
          total_area_union += area_union
          total_area_pred_label += area_pred_label
          total_area_label += area_label
     return total_area_intersect, total_area_union, total_area_pred_label, total_area_label

def 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						Any						,  SCREAMING_SNAKE_CASE__     :						Tuple						,  SCREAMING_SNAKE_CASE__     :						Optional[Any]						,  SCREAMING_SNAKE_CASE__     :						bool						,  SCREAMING_SNAKE_CASE__     :						Optional[int] = None						,  SCREAMING_SNAKE_CASE__     :						Optional[Dict[int, int]] = None						,  SCREAMING_SNAKE_CASE__     :						bool = False						,  )  ->       List[str]:





     '''simple docstring'''

     _UpperCAmelCase    ,	_UpperCAmelCase    ,	_UpperCAmelCase    ,	_UpperCAmelCase      :     str        =   total_intersect_and_union(
         lowerCAmelCase__						,  lowerCAmelCase__						,  lowerCAmelCase__						,  lowerCAmelCase__						,  lowerCAmelCase__						,  lowerCAmelCase__    )

     # compute metrics
     _UpperCAmelCase      :     Union[str, Any]        =   {}

     _UpperCAmelCase      :     str        =   total_area_intersect.sum() / total_area_label.sum()
     _UpperCAmelCase      :     List[Any]        =   total_area_intersect / total_area_union
     _UpperCAmelCase      :     List[Any]        =   total_area_intersect / total_area_label

     _UpperCAmelCase      :     Any        =   np.nanmean(lowerCAmelCase__    )
     _UpperCAmelCase      :     Optional[int]        =   np.nanmean(lowerCAmelCase__    )
     _UpperCAmelCase      :     Dict        =   all_acc
     _UpperCAmelCase      :     List[Any]        =   iou
     _UpperCAmelCase      :     Optional[int]        =   acc

     if nan_to_num is not None:
          _UpperCAmelCase      :     List[str]        =   {metric: np.nan_to_num(lowerCAmelCase__						,  nan=lowerCAmelCase__    ) for metric, metric_value in metrics.items()}

     return metrics






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION	,      _KWARGS_DESCRIPTION						)
class      UpperCAmelCase_  (    datasets.Metric						):



      def 						snake_case_ (					self					:     List[Any]						):
           return datasets.MetricInfo(
               description=_DESCRIPTION					,     citation=_CITATION					,     inputs_description=_KWARGS_DESCRIPTION					,     features=datasets.Features(
                   # 1st Seq - height dim, 2nd - width dim
                   {
                       "predictions": datasets.Sequence(datasets.Sequence(datasets.Value("uint16"						)						)						),
                       "references": datasets.Sequence(datasets.Sequence(datasets.Value("uint16"						)						)						),
                   }						)					,     reference_urls=[
                   "https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py"
               ]					,     )



      def 						snake_case_ (					self					:     List[str]					,     A					:     List[Any]					,     A					:     Union[str, Any]					,     A					:     Optional[int]					,     A					:     Optional[int]					,     A					:     Dict = None					,     A					:     Tuple = None					,     A					:     Union[str, Any] = False					,     ):
           _UpperCAmelCase      :     int        =   mean_iou(
               results=_a					,     gt_seg_maps=_a					,     num_labels=_a					,     ignore_index=_a					,     nan_to_num=_a					,     label_map=_a					,     reduce_labels=_a					,     )
           return iou_result










"""simple docstring"""




from typing import Dict, Iterable, List, Optional, Union

import numpy as np

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


_lowerCAmelCase    : Tuple							=							logging.get_logger(__name__)






class      UpperCAmelCase_  (    _UpperCamelCase						):
      __SCREAMING_SNAKE_CASE						:       str								=			['pixel_values']



      def __init__(					self					:     List[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, Iterable[float]]] = IMAGENET_DEFAULT_MEAN					,     A					:     Optional[Union[float, Iterable[float]]] = IMAGENET_DEFAULT_STD					,     **A					:     List[Any]					,     ):
           super().__init__(**A						)
           _UpperCAmelCase      :     int        =   size if size is not None else {"shortest_edge": 2_2_4}
           _UpperCAmelCase      :     Tuple        =   get_size_dict(A					,     default_to_square=A						)
           _UpperCAmelCase      :     int        =   crop_size if crop_size is not None else {"height": 2_2_4, "width": 2_2_4}
           _UpperCAmelCase      :     Union[str, Any]        =   get_size_dict(A					,     param_name="crop_size"						)

           _UpperCAmelCase      :     str        =   do_resize
           _UpperCAmelCase      :     Union[str, Any]        =   size
           _UpperCAmelCase      :     Tuple        =   resample
           _UpperCAmelCase      :     List[Any]        =   do_center_crop
           _UpperCAmelCase      :     List[Any]        =   crop_size
           _UpperCAmelCase      :     Tuple        =   do_rescale
           _UpperCAmelCase      :     List[Any]        =   rescale_factor
           _UpperCAmelCase      :     Dict        =   do_normalize
           _UpperCAmelCase      :     Optional[Any]        =   image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
           _UpperCAmelCase      :     Any        =   image_std if image_std is not None else IMAGENET_DEFAULT_STD



      def 						snake_case_ (					self					:     Optional[int]					,     A					:     np.ndarray					,     A					:     Dict[str, int]					,     A					:     PILImageResampling = PILImageResampling.BICUBIC					,     A					:     Optional[Union[str, ChannelDimension]] = None					,     **A					:     Union[str, Any]					,     ):
           _UpperCAmelCase      :     Tuple        =   get_size_dict(A					,     default_to_square=A						)
           # size_dict is a dict with either keys "height" and "width" or "shortest_edge"
           if "shortest_edge" in size:
                _UpperCAmelCase      :     Any        =   int((2_5_6 / 2_2_4) * size["shortest_edge"]						)
                _UpperCAmelCase      :     Union[str, Any]        =   get_resize_output_image_size(A					,     size=A					,     default_to_square=A						)
                _UpperCAmelCase      :     str        =   {"height": output_size[0], "width": output_size[1]}
           if "height" not in size_dict or "width" not in size_dict:
                raise ValueError(
                    f'Size dict must have keys \'height\' and \'width\' or \'shortest_edge\'. Got {size_dict.keys()}'						)
           return resize(
               A					,     size=(size_dict["height"], size_dict["width"])					,     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					:     Optional[Any]					,     ):
           _UpperCAmelCase      :     Dict        =   get_size_dict(A						)
           if "height" not in size or "width" not in size:
                raise ValueError(f'Size dict must have keys \'height\' and \'width\'. Got {size.keys()}'						)
           return center_crop(A					,     size=(size["height"], size["width"])					,     data_format=A					,     **A						)



      def 						snake_case_ (					self					:     List[str]					,     A					:     np.ndarray					,     A					:     Union[int, float]					,     A					:     Optional[Union[str, ChannelDimension]] = None					,     **A					:     Dict					,     ):
           return rescale(A					,     scale=A					,     data_format=A					,     **A						)



      def 						snake_case_ (					self					:     List[str]					,     A					:     np.ndarray					,     A					:     Union[float, List[float]]					,     A					:     Union[float, List[float]]					,     A					:     Optional[Union[str, ChannelDimension]] = None					,     **A					:     str					,     ):
           return normalize(A					,     mean=A					,     std=A					,     data_format=A					,     **A						)



      def 						snake_case_ (					self					:     Tuple					,     A					:     ImageInput					,     A					:     Optional[bool] = None					,     A					:     Optional[Dict[str, int]] = None					,     A					:     PILImageResampling = None					,     A					:     Optional[bool] = None					,     A					:     Optional[Dict[str, int]] = None					,     A					:     Optional[bool] = None					,     A					:     Optional[float] = None					,     A					:     Optional[bool] = None					,     A					:     Optional[Union[float, Iterable[float]]] = None					,     A					:     Optional[Union[float, Iterable[float]]] = None					,     A					:     Optional[TensorType] = None					,     A					:     ChannelDimension = ChannelDimension.FIRST					,     **A					:     Dict					,     ):
           _UpperCAmelCase      :     Dict        =   do_resize if do_resize is not None else self.do_resize
           _UpperCAmelCase      :     List[str]        =   resample if resample is not None else self.resample
           _UpperCAmelCase      :     int        =   do_center_crop if do_center_crop is not None else self.do_center_crop
           _UpperCAmelCase      :     str        =   do_rescale if do_rescale is not None else self.do_rescale
           _UpperCAmelCase      :     Tuple        =   rescale_factor if rescale_factor is not None else self.rescale_factor
           _UpperCAmelCase      :     Optional[int]        =   do_normalize if do_normalize is not None else self.do_normalize
           _UpperCAmelCase      :     List[str]        =   image_mean if image_mean is not None else self.image_mean
           _UpperCAmelCase      :     Tuple        =   image_std if image_std is not None else self.image_std

           _UpperCAmelCase      :     Any        =   size if size is not None else self.size
           _UpperCAmelCase      :     Optional[int]        =   get_size_dict(A					,     default_to_square=A						)
           _UpperCAmelCase      :     List[str]        =   crop_size if crop_size is not None else self.crop_size
           _UpperCAmelCase      :     List[str]        =   get_size_dict(A					,     param_name="crop_size"						)

           _UpperCAmelCase      :     List[Any]        =   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."						)

           # All transformations expect numpy arrays.
           _UpperCAmelCase      :     Any        =   [to_numpy_array(A						) for image in images]

           if do_resize:
                _UpperCAmelCase      :     str        =   [self.resize(A					,     A					,     A						) for image in images]

           if do_center_crop:
                _UpperCAmelCase      :     Dict        =   [self.center_crop(A					,     A						) for image in images]

           if do_rescale:
                _UpperCAmelCase      :     Dict        =   [self.rescale(A					,     A						) for image in images]

           if do_normalize:
                _UpperCAmelCase      :     Optional[int]        =   [self.normalize(A					,     A					,     A						) for image in images]

           _UpperCAmelCase      :     Union[str, Any]        =   [to_channel_dimension_format(A					,     A						) for image in images]

           _UpperCAmelCase      :     List[Any]        =   {"pixel_values": images}
           return BatchFeature(data=A					,     tensor_type=A						)
