
    ^j}                       d dl mZ d dlZd dlZd dlZd dlZd dlmZ d dlm	Z	 d dl
mZmZmZ d dlZd dlZd dlm
Z d dlmZmZ d dlmZ d dlmZ d d	lmZmZ d d
lmZmZ d dl m!Z! d dl"m#Z#m$Z$m%Z% d dl&m'Z'm(Z( ed   Z)dZ*e$	 	 	 	 	 	 d3d       Z+e$d4d       Z,e$	 d5	 	 	 	 	 	 	 d6d       Z-e$ej\                  f	 	 	 	 	 	 	 d7d       Z/ eej`                  dd      	 	 	 	 	 	 	 	 d8d       Z1e$ej\                  df	 	 	 	 	 	 	 d9d       Z2e$d:d       Z3d;dZ4 G d d      Z5 eej`                  dd      ddd ejl                  d      d  ejl                  d!      d"dd ejl                  d#      dd$d ejn                   ejl                  d      d%f	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d<d&       Z8d=d'Z9	 	 	 	 	 	 d>d(Z: e	e:ejv                  )       e	e:ejx                  )       e	e:ejz                  )      d*Z>	 	 	 	 	 	 d?d+Z?	 	 	 	 	 	 d@d,Z@dAd-ZA	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dBd.ZB	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dCd/ZC	 	 	 	 	 	 	 	 dDd0ZD	 	 	 	 	 	 	 	 	 	 	 	 dEd1ZE	 	 	 	 	 	 dFd2ZFy)G    )annotationsN)Callable)partial)AnyLiteralcast)
TargetMode
deprecated)Image)	ImageType)Colorunify_to_bgr)calculate_optimal_text_scale	draw_text)Point)cv2_to_pillow(ensure_cv2_image_for_standalone_functionimages_to_cv2)create_batchesfill)topbottom   c                   t        |t        t        f      rt        j                  |      }t        j
                  |      j                  t              }|j                         \  }}}}t        | t        j                        r| ||||f   S t        | t        j                        r| j                  ||||f      S t        dt        |              )a(  
    Crop image based on bounding box coordinates.

    Args:
        image: The image to crop.
        xyxy:
            Bounding box coordinates in `(x_min, y_min, x_max, y_max)` format.

    Returns:
        Cropped image matching input
            type.

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((1080, 1920, 3), dtype=np.uint8)
        >>> image.shape
        (1080, 1920, 3)
        >>> xyxy = (400, 400, 800, 800)
        >>> cropped_image = sv.crop_image(image=image, xyxy=xyxy)
        >>> cropped_image.shape
        (400, 400, 3)

        ```

        ```pycon
        >>> image = np.zeros((1920, 1080), dtype=np.uint8)
        >>> image.shape
        (1920, 1080)
        >>> xyxy = (400, 400, 800, 800)
        >>> cropped_image = sv.crop_image(image=image, xyxy=xyxy)
        >>> cropped_image.shape
        (400, 400)

        ```

    ![crop-image](https://media.roboflow.com/supervision-docs/supervision-docs-crop-image-2.png){ align=center width="1000" }
    z=`image` must be a numpy.ndarray or PIL.Image.Image. Received )
isinstancelisttuplenparrayroundastypeintflattenndarrayr   crop	TypeErrortype)imagexyxyx_miny_minx_maxy_maxs         b/var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/supervision/utils/image.py
crop_imager/   !   s    X $u&xx~88D>  %D!%E5%%$U5[%+-..%%zz5%677

GU}U     c                   t        | t        j                        sJ |dk  rt        d      | j                  d   | j                  d   }}t        ||z        }t        ||z        }t        j                  | ||ft        j                        S )a"  
    Scale image by given factor. Scale factor > 1.0 zooms in, < 1.0 zooms out.

    Args:
        image: The image to scale.
        scale_factor: Factor by which to scale the image.

    Returns:
        Scaled image matching input
            type.

    Raises:
        ValueError: If scale factor is non-positive.

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((1080, 1920, 3), dtype=np.uint8)
        >>> image.shape
        (1080, 1920, 3)
        >>> scaled_image = sv.scale_image(image=image, scale_factor=0.5)
        >>> scaled_image.shape
        (540, 960, 3)

        ```

        ```pycon
        >>> image = np.zeros((1920, 1080), dtype=np.uint8)
        >>> image.shape
        (1920, 1080)
        >>> scaled_image = sv.scale_image(image=image, scale_factor=0.5)
        >>> scaled_image.shape
        (960, 540)

        ```

    ![scale-image](https://media.roboflow.com/supervision-docs/supervision-docs-scale-image-2.png){ align=center width="1000" }
    r   zScale factor must be positive.   interpolation)	r   r   r$   
ValueErrorshaper"   cv2resizeINTER_LINEAR)r(   scale_factor	width_old
height_old	width_new
height_news         r.   scale_imager?   ^   s    R eRZZ(((q9::!KKNEKKNzII,-IZ,./J::ei4CDTDTUUr0   c                R   t        | t        j                        sJ |r]| j                  d   | j                  d   z  }|d   |d   z  }||k\  r|d   }t	        |d   |z        }n|d   }t	        |d   |z        }n|\  }}t        j                  | ||ft
        j                        S )a  
    Resize image to specified resolution. Can optionally maintain aspect ratio.

    Args:
        image: The image to resize.
        resolution_wh: Target resolution as `(width, height)`.
        keep_aspect_ratio: Flag to maintain original aspect ratio.
            Defaults to `False`.

    Returns:
        Resized image matching input
            type.

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((1080, 1920, 3), dtype=np.uint8)
        >>> image.shape
        (1080, 1920, 3)
        >>> resized_image = sv.resize_image(
        ...     image=image, resolution_wh=(1000, 1000), keep_aspect_ratio=True
        ... )
        >>> resized_image.shape
        (562, 1000, 3)

        ```

        ```pycon
        >>> image = np.zeros((1920, 1080), dtype=np.uint8)
        >>> image.shape
        (1920, 1080)
        >>> resized_image = sv.resize_image(
        ...     image=image, resolution_wh=(1000, 1000), keep_aspect_ratio=True
        ... )
        >>> resized_image.shape
        (1000, 562)

        ```

    ![resize-image](https://media.roboflow.com/supervision-docs/supervision-docs-resize-image-2.png){ align=center width="1000" }
    r2   r   r3   )r   r   r$   r6   r"   r7   r8   r9   )r(   resolution_whkeep_aspect_ratioimage_ratiotarget_ratior=   r>   s          r.   resize_imagerE      s    ` eRZZ(((kk!nu{{1~5$Q'-*::,&%a(I]1-;<J&q)JM!,{:;I -	:::ei4CDTDTUUr0   c           	     B   t        | t        j                        sJ t        |      }t	        | |d      }|j
                  dd \  }}|d   |z
  dz  }|d   |z
  |z
  }|d   |z
  dz  }|d   |z
  |z
  }	t        j                  |||||	t        j                  |      }
|
S )	a  
    Resize image and pad with color to achieve desired resolution while
    maintaining aspect ratio.

    Args:
        image: The image to resize and pad. Accepts BGR arrays of shape
            ``(H, W, 3)``, BGRA arrays of shape ``(H, W, 4)``, grayscale
            arrays of shape ``(H, W)``, or a PIL ``Image``.
        resolution_wh: Target resolution as `(width, height)`.
        color: Padding color. If tuple, should be in BGR format.
            Defaults to `Color.BLACK`.

    Returns:
        Letterboxed image matching input type.

    Note:
        For BGRA inputs, the alpha channel in the padding region is set to
        0 (fully transparent). Grayscale inputs receive scalar padding
        from ``color[0]``.

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((1080, 1920, 3), dtype=np.uint8)
        >>> image.shape
        (1080, 1920, 3)
        >>> letterboxed_image = sv.letterbox_image(
        ...     image=image, resolution_wh=(1000, 1000)
        ... )
        >>> letterboxed_image.shape
        (1000, 1000, 3)
        >>> gray = np.zeros((4, 6), dtype=np.uint8)
        >>> sv.letterbox_image(image=gray, resolution_wh=(10, 10)).shape
        (10, 10)

        ```

    ![letterbox-image](https://media.roboflow.com/supervision-docs/supervision-docs-letterbox-image-2.png){ align=center width="1000" }
    colorT)r(   rA   rB   N   r2   r   )value)	r   r   r$   r   rE   r6   r7   copyMakeBorderBORDER_CONSTANT)r(   rA   rH   resized_imager>   r=   padding_toppadding_bottompadding_leftpadding_rightimage_with_borderss              r.   letterbox_imagerS      s    \ eRZZ(((u%E =DM *//3J	 #j0Q6K"1%
2[@N!!$y0Q6L!!$y0<?M++ r0   z0.27.0z0.31.0)targetdeprecated_in	remove_inc                   | j                   dd \  }}|j                   dd \  }}|\  }}||z   dk  xs ||k\  }	||z   dk  xs ||k\  }
|	s|
r| S t        |d      }t        |d      }t        |||z         }t        |||z         }t        | d      }t        | d      }|t        ||z   |z
  d      z
  }|t        ||z   |z
  d      z
  }|j                   d   dk(  rst        j                  |||||f         \  }}}}|dddddf   dz  }t        j
                  |||f      }| ||||f   }|d|z
  z  ||z  z   |dd || ||||f<   | S |||||f   | ||||f<   | S )a  
    Overlay image onto scene at specified anchor point. Handles cases where
    overlay position is partially or completely outside scene bounds.

    Args:
        image: Background scene with shape `(height, width, 3)`.
        overlay: Image to overlay with shape
            `(height, width, 3)` or `(height, width, 4)`.
        anchor: Coordinates `(x, y)` where top-left corner
            of overlay will be placed.

    Returns:
        Scene with overlay applied, shape `(height, width, 3)`.

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((1000, 1000, 3), dtype=np.uint8)
        >>> overlay = np.zeros((400, 400, 3), dtype=np.uint8)
        >>> overlay[:] = (0, 255, 0)  # Green overlay
        >>> result_image = sv.overlay_image(
        ...     image=image, overlay=overlay, anchor=(200, 400)
        ... )
        >>> result_image.shape
        (1000, 1000, 3)

        ```
    NrI   r      g     o@r2   )r6   maxminr7   splitmerge)r(   overlayanchorscene_heightscene_widthimage_heightimage_widthanchor_xanchor_yis_out_horizontallyis_out_verticallyr*   r+   r,   r-   
crop_x_min
crop_y_min
crop_x_max
crop_y_maxbgralphaoverlay_colorrois                            r.   overlay_imagerq     s   N !&BQL+ 'bq 1L+Hh"[0A5P[9P </14PL8P/!E!EX34Eh56EhY"JhY"JsH{$:k#I1MMJX%<$La PPJ}}Q1Jz):j+@@A
1a aDj!E)		1a),E%Ku,-E	"]U%::A*-eEk5;&' L	 +2z!:j#88+
eEk5;&' Lr0   g      ?c                   t        | t        j                        sJ d|cxk  rdk  st        d       t        d      t        j                  | |j                         | j                        }t        j                  ||| d|z
  d|        | S )aw  
    Tint image with solid color overlay at specified opacity.

    Args:
        image: The image to tint.
        color: Overlay tint color. Defaults to `Color.BLACK`.
        opacity: Blend ratio between overlay and image (0.0-1.0).
            Defaults to `0.5`.

    Returns:
        Tinted image matching input
            type.

    Raises:
        ValueError: If opacity is outside range [0.0, 1.0].

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((100, 100, 3), dtype=np.uint8)
        >>> tinted_image = sv.tint_image(
        ...     image=image, color=sv.Color.ROBOFLOW, opacity=0.5
        ... )
        >>> tinted_image.shape
        (100, 100, 3)

        ```

    ![tint-image](https://media.roboflow.com/supervision-docs/supervision-docs-tint-image-2.png){ align=center width="1000" }
    g        g      ?z#opacity must be between 0.0 and 1.0)
fill_valuedtyper2   r   )src1rn   src2betagammadst)	r   r   r$   r5   	full_likeas_bgrrt   r7   addWeighted)r(   rH   opacityr]   s       r.   
tint_imager~   c  s    J eRZZ(((' S >?? !>??ll5U\\^5;;OGOOG%a'kPU Lr0   c                    t        j                  | t         j                        }t        j                  |t         j                        S )a  
    Convert image to 3-channel grayscale. Luminance channel is broadcast to
    all three channels for compatibility with color-based drawing helpers.

    Args:
        image: The image to convert to
            grayscale.

    Returns:
        3-channel grayscale image
            matching input type.

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.ones((100, 100, 3), dtype=np.uint8) * 128
        >>> grayscale_image = sv.grayscale_image(image=image)
        >>> grayscale_image.shape
        (100, 100, 3)

        ```

    ![grayscale-image](https://media.roboflow.com/supervision-docs/supervision-docs-grayscale-image-2.png){ align=center width="1000" }
    )r7   cvtColorCOLOR_BGR2GRAYCOLOR_GRAY2BGR)r(   
grayscaleds     r.   grayscale_imager     s1    6 eS%7%78J<<
C$6$677r0   c                   t        | t        j                        rO| j                  dk  rt	        d| j
                         | j
                  dd \  }}t        |      t        |      fS t        | t        j                        r%| j                  \  }}t        |      t        |      fS t        dt        |              )a  
    Get image width and height as a tuple `(width, height)` for various image formats.

    Supports both `numpy.ndarray` images (with shape `(H, W, ...)`) and
    `PIL.Image.Image` inputs.

    Args:
        image: Input image.

    Returns:
        Image resolution as `(width, height)`.

    Raises:
        ValueError: If a `numpy.ndarray` image has fewer than 2 dimensions.
        TypeError: If `image` is not a supported type (`numpy.ndarray` or
            `PIL.Image.Image`).

    Examples:
        ```pycon
        >>> import numpy as np
        >>> import supervision as sv
        >>> image = np.zeros((1080, 1920, 3), dtype=np.uint8)
        >>> sv.get_image_resolution_wh(image)
        (1920, 1080)

        ```
    rI   zINumPy image must have at least 2 dimensions (H, W, ...). Received shape: NzC`image` must be a numpy.ndarray or PIL.Image.Image. Received type: )r   r   r$   ndimr5   r6   r"   r   sizer&   r'   )r(   heightwidths      r.   get_image_resolution_whr     s    8 %$::>##(;;-1  BQ5z3v;&&%%

v5z3v;&&
	u+	( r0   c                  Z    e Zd Z	 	 d	 	 	 	 	 ddZddZ	 d		 	 	 	 	 d
dZ	 	 	 	 	 	 	 	 ddZy)	ImageSinkc                <    || _         || _        || _        d| _        y)a  
        Initialize context manager for saving images to directory.

        Args:
            target_dir_path: Target directory path where images will be
                saved.
            overwrite: Whether to overwrite existing directory.
                Defaults to `False`.
            image_name_pattern: File name pattern for saved images.
                Defaults to `"image_{:05d}.png"`.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> import supervision as sv
            >>> import tempfile
            >>> import os
            >>> with tempfile.TemporaryDirectory() as tmpdir:
            ...     image = np.zeros((100, 100, 3), dtype=np.uint8)
            ...     with sv.ImageSink(target_dir_path=tmpdir, overwrite=True) as sink:
            ...         sink.save_image(image=image)
            ...         sink.save_image(image=image)
            ...     files = sorted(os.listdir(tmpdir))
            ...     len(files)
            2

            ```
        r   N)target_dir_path	overwriteimage_name_patternimage_count)selfr   r   r   s       r.   __init__zImageSink.__init__  s$    D  /""4r0   c                .   t         j                  j                  | j                        rL| j                  r>t        j                  | j                         t        j                  | j                         | S t        j                  | j                         | S N)ospathexistsr   r   shutilrmtreemakedirs)r   s    r.   	__enter__zImageSink.__enter__	  sc    77>>$../~~d223D001  KK,,-r0   Nc                    |%| j                   j                  | j                        }t        j                  j                  | j                  |      }t        j                  ||       | xj                  dz  c_        y)aa  
        Save image to target directory with optional custom filename.

        Args:
            image: Image to save with shape `(height, width, 3)`
                in BGR format.
            image_name: Custom filename for saved image. If
                `None`, generates name using `image_name_pattern`. Defaults to
                `None`.
        Nr2   )	r   formatr   r   r   joinr   r7   imwrite)r   r(   
image_name
image_paths       r.   
save_imagezImageSink.save_image  s_     00778H8HIJWW\\$"6"6
C
J&Ar0   c                     y r    )r   exc_type	exc_valueexc_tracebacks       r.   __exit__zImageSink.__exit__'  s     	r0   )Fzimage_{:05d}.png)r   strr   boolr   r   )returnr   r   )r(   npt.NDArray[np.uint8]r   z
str | Noner   None)r   ztype[BaseException] | Noner   zBaseException | Noner   r   r   r   )__name__
__module____qualname__r   r   r   r   r   r0   r.   r   r     s      "4	%% %  	%N FJ*8B	(, ( 	
 
r0   r   avgz#D9D9D9
   z#BFBEBDautoz#262523r2   r   c                   t        |       dk(  rt        d      |dk(  rt        |       }t        |      }t        |      }t	        |       } |t        | |      }| D cg c]  }t        |||       }}t        | |	      }t        |       |d   |d
   z  kD  rt        dt        |        d| d      |t        |t        |       d      }t        |	t              r|	}n|	g}t        |t        |       d      }	t        |
      }
t        |      }t        ||||||||	|
||||||      }|dk(  rt        |      }t        t        |      S c c}w )a  
    Creates tiles mosaic from input images, automating grid placement and
    converting images to common resolution maintaining aspect ratio. It is
    also possible to render text titles on tiles, using optional set of
    parameters specifying text drawing (see parameters description).

    Automated grid placement will try to maintain square shape of grid
    (with size being the nearest integer square root of #images), up to two exceptions:
    * if there are up to 3 images - images will be displayed in single row
    * if square-grid placement causes last row to be empty - number of rows is trimmed
        until last row has at least one image

    Args:
        images: Images to create tiles. Elements can be either np.ndarray or
            PIL.Image, and a common representation will be agreed by the
            function.
        grid_size: Expected grid size in format (n_rows, n_cols). If not
            given, automated grid placement will be applied. One may also
            provide only one out of two elements of the tuple - then grid
            will be created with either n_rows or n_cols fixed, leaving the
            other dimension to be adjusted by the number of images.
        single_tile_size: Size of a single tile element provided in
            (width, height) format. If not given, size of tile will be
            automatically calculated based on `tile_scaling`.
        tile_scaling: Strategy used to calculate tile size when
            `single_tile_size` is not given, using the min / max / avg size
            of images provided in `images`.
        tile_padding_color: Color to be used in the image letterbox procedure
            while standardizing tile sizes. If a tuple is provided, it should
            be in BGR order.
        tile_margin: Size of margin between tiles, in pixels.
        tile_margin_color: Color of the tile margin. If a tuple is provided,
            it should be in BGR order.
        return_type: Format of the returned image. One may choose a specific
            format ("cv2" or "pillow") to enforce conversion. "auto" mode
            takes a majority vote between types of elements in `images`,
            resolving draws in favour of OpenCV format. "auto" can be safely
            used when all input images are of the same type.
        titles: Optional titles to be added to tiles. Elements of that list
            may be empty - then a specific tile, in the order presented in
            `images`, will not be filled with a title. It is possible to
            provide a list of titles shorter than `images` - then remaining
            titles will be assumed empty.
        titles_anchors: Anchor points for titles. It is possible to specify
            an anchor either globally or for specific tiles, following the
            order of `images`. If not given, either globally or for a
            specific element of the list, it will be calculated
            automatically based on `default_title_placement`.
        titles_color: Color of the title text. If a tuple is provided, it
            should be in BGR order.
        titles_scale: Scale of titles. If not provided, the value will be
            calculated using `calculate_optimal_text_scale(...)`.
        titles_thickness: Thickness of title text.
        titles_padding: Size of title padding.
        titles_text_font: Font used to render titles. Must be an integer
            constant representing an OpenCV font.
            (See docs: https://docs.opencv.org/4.x/d6/d6e/group__imgproc__draw.html)
        titles_background_color: Color of the title text padding.
        default_title_placement: Title anchor placement used when an explicit
            anchor is not provided.

    Returns:
        ImageType: Image with all input images located in tiles grid. The output type is
            determined by `return_type` parameter.

    Raises:
        ValueError: In case when input images list is empty, provided `grid_size` is too
            small to fit all images, `tile_scaling` mode is invalid.
    r   z7Could not create image tiles from empty list of images.r   imagesrG   Nr   mode)r(   rA   rH   )r   	grid_sizer2   zCould not place z in grid with size: .)sequencedesired_sizecontent)r   r   single_tile_sizetile_padding_colortile_margintile_margin_colortitlestitles_anchorstitles_colortitles_scaletitles_thicknesstitles_paddingtitles_text_fonttitles_background_colordefault_title_placementpillow)r(   )lenr5   _negotiate_tiles_formatr   r   _aggregate_images_shaperS   _establish_grid_sizer   r   r   _generate_tilesr   r   r   )r   r   r   tile_scalingr   r   r   return_typer   r   r   r   r   r   r   r   r   iresized_imagestitles_anchors_sequencetiless                        r.   create_tilesr   0  s   z 6{aRSSf-V<%,>?$+<=&)F2&|T
 	  	#3;M	
N  %FiHI
6{Yq\IaL00s6{m+?	{!L
 	
 vCKN.$'"0#1"2(s6{DN  l3L*1HI)-+%!!)%) 7 7E" hE*	5!!Ss   "Ec                L    t        d | D              }|dz  t        |       k\  ryy)Nc              3  b   K   | ]'  }t        t        |      t        j                         ) y wr   )
issubclassr'   r   r$   ).0r   s     r.   	<genexpr>z*_negotiate_tiles_format.<locals>.<genexpr>  s     N!ja"**=Ns   -/rI   r7   r   )sumr   )r   number_of_np_arrayss     r.   r   r     s*    NvNNQ#f+-r0   c           	         t         || D cg c]  }|j                  d    c}            }t         || D cg c]  }|j                  d    c}            }||fS c c}w c c}w )Nr   r2   )r    r6   )r   
aggregatorr   r   r   s        r.   "_calculate_aggregated_images_shaper     sZ     :6:aqwwqz:;<F*&9Qaggaj9:;E&= ;9s
   AA")r   )rZ   rY   r   c           	         |t         vr-t        d| dt        t         j                                d      t        |   |       S )Nz:Could not aggregate images shape - provided unknown mode: z. Supported modes: r   )SHAPE_AGGREGATION_FUNr5   r   keysr   s     r.   r   r     sV     ((H O  $%:%?%?%A BC1F
 	
 !&v..r0   c                @   |t        d |D              rt        |       S |d   ,|d   }|J t        j                  t	        |       |z        |fS |d   ,|d   }|J |t        j                  t	        |       |z        fS t        t        t        t        f   |      S )Nc              3  $   K   | ]  }|d u  
 y wr   r   )r   es     r.   r   z'_establish_grid_size.<locals>.<genexpr>  s     =aT	=s   r   r   r2   )all_negotiate_grid_sizemathceilr   r   r   r"   )r   r   columnsrowss       r.   r   r     s     C=9==#622|A,"""yyVw./88||TYYs6{T1222c3h++r0   c                   t        |       t        k  rdt        |       fS t        j                  t	        j
                  t        |                   }|}|}||dz
  z  t        |       k\  r|dz  }||dz
  z  t        |       k\  r||fS )Nr2   )r   MAX_COLUMNS_FOR_SINGLE_ROW_GRIDr   r   r   sqrt)r   nearest_sqrtproposed_columnsproposed_rowss       r.   r   r     s    
6{55#f+~99RWWS[12L# M
ma/
0CK
? ma/
0CK
?***r0   c                   t        | ||||	|
||||
      } |\  }}t        t        | |            }t        |d         |k  r1|d   j	                  t        ||             t        |d         |k  r1t        |      |k  r/|j	                  t        ||      g|z         t        |      |k  r/t        |||||      S )N)
r   r   r   r   r   r   r   r   r   r   )r   
batch_sizer6   rH   )tiles_elementsr   r   r   r   )_draw_textsr   r   r   append_generate_color_image_merge_tiles_elements)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   s                     r.   r   r     s    " %!!)%) 7 7F MD'.&WMNN
nR 
!G
+r!!!(8@RS	
 nR 
!G
+ n

$")9ASTU	
 n

$
 !%)+ r0   c
                b   || S t        | ||	      }
|#| d   j                  d d \  }}t        ||f      }g }t        | ||
      D ]e  \  }}}||j	                  |       t        |||t        j                  |      ||||t        j                  |      	      }|j	                  |       g |S )N)r   r   r   r   rI   )rA   )	scenetexttext_anchor
text_color
text_scaletext_thicknesstext_padding	text_fontbackground_color)_prepare_default_titles_anchorsr6   r   zipr   r   r   from_bgr_tuple)r   r   r   r   r   r   r   r   r   r   prepared_titles_anchorsra   rb   resultr(   r   r^   processed_images                     r.   r   r   0  s     ~=% 7
 $*1IOOBQ$7!k3&5
 F"663JK 'tV<MM% #++L9#+'&"112IJ

 	o&'  Mr0   c                    g }t        | |      D ]h  \  }}||j                  |       |j                  d d \  }}|dk(  rt        |dz  |dz        }nt        |dz  |dz        }|j                  |       j |S )NrI   r   g?)xyg?)r	  r   r6   r   )	r   r   r   r  r(   r^   ra   rb   default_anchors	            r.   r  r  \  s    
 FV^4 	&vMM&!$)KKO!k"e+"[1_s8JKN"[1_s8JKNn%	& Mr0   c                   t        j                  |d   |dft         j                        |z  }| D cg c]S  }t        j                  t	        t
        j                  j                  t        ||g|d   z                    d d d      U }}|d   j                  d   }t        j                  ||dft         j                        |z  }	g }
|D ]$  }|
j                  |       |
j                  |	       & t        t        j                  t         j                     t        j                  |
d d d      j                  t         j                              S c c}w )Nr2   r   rt   r   )axisr   )r   onesuint8concatenater   	itertoolschainfrom_iterabler	  r6   r   r   nptNDArrayr!   )r   r   r   r   r   vertical_paddingrowmerged_rows	row_widthhorizontal_paddingrows_with_paddingss              r.   r   r   o  sW    	!!$k15RXXF
	  "
  	--./)A,>? r	
 	

K 
 A$$Q'I
i+288<?PP   6!!#&!!"456 BHH
s#	
 &
 '
s   AEc           
         t        t        j                  t        j                     t        j
                  g | d d d   dt        j                        |z        S )Nr   r   r  )r   r  r  r   r  r  r   s     r.   r   r     sK     BHH
!%"+!q!2U: r0   )r(   r   r)   z8npt.NDArray[int] | list[int] | tuple[int, int, int, int]r   r   )r(   r   r:   floatr   r   )F)r(   r   rA   tuple[int, int]rB   r   r   r   )r(   r   rA   r%  rH   tuple[int, int, int] | Colorr   r   )r(   r   r]   r   r^   r%  r   r   )r(   r   rH   r   r}   r$  r   r   )r(   r   r   r   )r(   r   r   r%  )$r   list[ImageType]r   $tuple[int | None, int | None] | Noner   ztuple[int, int] | Noner   Literal['min', 'max', 'avg']r   r&  r   r"   r   r&  r   z Literal['auto', 'cv2', 'pillow']r   list[str | None] | Noner   z!Point | list[Point | None] | Noner   r&  r   float | Noner   r"   r   r"   r   r"   r   r&  r   RelativePositionr   r   )r   r'  r   zLiteral['cv2', 'pillow'])r   list[npt.NDArray[np.uint8]]r   zCallable[[list[int]], float]r   r%  )r   r-  r   r)  r   r%  )r   r-  r   r(  r   r%  )r   r-  r   r%  ) r   r-  r   r%  r   r%  r   tuple[int, int, int]r   r"   r   r.  r   r*  r   list[Point | None]r   r.  r   r+  r   r"   r   r"   r   r"   r   r.  r   r,  r   r   )r   r-  r   r*  r   r/  r   r.  r   r+  r   r"   r   r"   r   r"   r   r.  r   r,  r   r-  )r   r-  r   r/  r   r,  r   zlist[Point])r   z!list[list[npt.NDArray[np.uint8]]]r   r%  r   r%  r   r"   r   r.  r   r   )r6   r%  rH   r.  r   r   )G
__future__r   r  r   r   r   collections.abcr   	functoolsr   typingr   r   r   r7   numpyr   numpy.typingr  	deprecater	   r
   PILr   supervision.draw.baser   supervision.draw.colorr   r   supervision.draw.utilsr   r   supervision.geometry.corer   supervision.utils.conversionr   r   r   supervision.utils.iterablesr   r   r,  r   r/   r?   rE   BLACKrS   NOTIFYrq   r~   r   r   r   from_hexFONT_HERSHEY_SIMPLEXr   r   r   rZ   rY   averager   r   r   r   r   r   r  r   r   r   r0   r.   <module>rC     sm   "   	  $  % % 
   ,  + 6 J + 
 =?+ "#  *99
B9 9 *9x */V */Vd * $<V<V"<V <V 	<V *<V~ * +0++AA"A (A 	A *AH 
E E"E E 	E
EP * ;;,,, , 	, *,^ *8 *8<,^L L^  7;/3167Eu~~i7P6DennY6O4:&*8<1?	1J!%44<JENN9<U05#J"J"3J" -J" /	J"
 5J" J" 4J" 2J" $J" 6J" /J" J" J" J" J"  :!J"" .#J"$ %J"
J"Z'5Q 5"&&I5"&&I5"**M /'//K//,',3, ,"+.'.. &. -	.
 . ,. $. '. '. . . . . 2. ..  !.b)')#) ') '	)
 ) ) ) ) 2) .) !)X'& . 	&$5$$ &$ 	$
 ,$ $N#7r0   