§
    >²¸j	ÿ  ã                  ó  — U d Z ddlmZ ddlZddlmZmZmZ ddlm	Z	m
Z
mZ ddlZddlmZ ddlmZmZmZmZ d5d„Z	 	 d6d7d„Zd8d„Zd9d„Zd:d„Zd;d!„Zd<d$„Zd%Zd&ed'<   d(Zd
ed)<   d*Zd
ed+<   d,Z d
ed-<   d=d2„Z! G d3„ d4¦  «        Z"dS )>u  Crop-RLE compact mask storage for memory-efficient instance segmentation.

Dense ``(N, H, W)`` boolean masks use O(NÂ·HÂ·W) memory, which becomes
prohibitive for aerial imagery (e.g. 1000 objects x 4K image ~ 8.3 GB).
:class:`CompactMask` stores each mask as a run-length encoding of its
bounding-box crop, reducing typical usage to tens of MB.

The bounding boxes (``xyxy``) already present in ``Detections`` serve as the
crop boundaries, so no extra metadata is required from the caller.

CompactMask reduces memory footprint but does not improve computational
speed. The ingestion path (base48 decode, column split, RLE trim) is
Python-level and is typically slower than the dense NumPy path. The primary
benefit is memory savings for large images with many sparse masks.
é    )ÚannotationsN)ÚIteratorÚMappingÚSequence)ÚAnyÚcastÚoverload)Ú_base48_decodeÚ_delta_decodeÚ_mask_to_rle_countsÚ_rle_counts_to_maskÚrleúnpt.NDArray[np.int32]ÚreturnÚintc                óV   — t          t          j        | ddd…         ¦  «        ¦  «        S )aÏ  Return the number of ``True`` pixels in a run-length encoded mask.

    Args:
        rle: int32 array of run lengths as produced by :func:`_mask_to_rle_counts`.

    Returns:
        Total number of ``True`` pixels.

    Examples:
        ```pycon
        >>> import numpy as np
        >>> from supervision.detection.compact_mask import _rle_area
        >>> rle = np.array([1, 2, 1, 1, 1], dtype=np.int32)
        >>> _rle_area(rle)
        3

        ```
    é   Né   )r   ÚnpÚsum)r   s    úr/root/private/project/pallet_detection_v2/.venv/lib/python3.11/site-packages/supervision/detection/compact_mask.pyÚ	_rle_arear   %   s&   € õ& �rŒv�c˜!˜$˜Q˜$”iÑ Ô Ñ!Ô!Ð!ó    Úcrop_hÚcrop_wÚx_startÚx_stopú
int | Noneúlist[list[int]]c                ó’  — |€|dz
  }|                       ¦   «         }||z
  dz   }d„ t          |¦  «        D ¦   «         }||z  }|dk    r¥t          |¦  «        dk    r’t          j        | t          j        ¬¦  «        }	t          t          j        |	|d¬¦  «        ¦  «        }
|
t          |¦  «        k    rt          |¦  «        D ]}|g||<   Œ	|S |
dk    rt          |	|
dz
           ¦  «        nd}nd}
d}||z  }||z  }t          |
t          |¦  «        ¦  «        D �]}||         }|dz  dk    }|}|dk    ré||k    rd}nà||z
  }t          ||¦  «        }||k    r¨||z
  }t          ||         ¦  «        dk    r|r||          	                    d¦  «         nQ|t          ||         ¦  «        dz
  dz  dk    k    r.||         d	xx         |z  cc<   ||z  }||z  }||k    rd}|dz  }Œ·||          	                    |¦  «         ||z  }||z  }||k    rd}|dz  }|dk    °é||k    r n�Œt          |¦  «        D ]}||         s|g||<   Œ|S )
aÀ  Split a flat F-order RLE into per-column run lists.

    With F-order (column-major) RLE the flat pixel sequence visits all rows
    of column 0, then all rows of column 1, etc.  Each column therefore
    contains ``crop_h`` contiguous pixels.

    Runs that cross column boundaries are split at the boundary.  Each
    returned list starts with a ``False``-run count (possibly 0), matching
    the convention of :func:`_mask_to_rle_counts`.

    When ``x_start`` and ``x_stop`` are provided, only columns in the closed
    range ``[x_start, x_stop]`` are collected.  Pixels in skipped columns
    are consumed without being stored, which avoids O(W) allocation when
    only a small crop of a wide image is needed.

    Note:
        ``x_start`` uses ``np.cumsum`` + ``np.searchsorted`` to jump directly
        to the first relevant run in O(log R) time, avoiding the O(pixel_prefix)
        walk that previously made right-edge crops on wide images expensive.

    Args:
        rle: int32 run-length array as produced by
            :func:`~supervision.detection.utils.converters._mask_to_rle_counts`.
        crop_h: Number of rows (pixels per column).
        crop_w: Number of columns.
        x_start: First column to collect (0-indexed, inclusive).  Columns
            before ``x_start`` are skipped.  Defaults to ``0``.
        x_stop: Last column to collect (0-indexed, inclusive).  Processing
            stops after column ``x_stop`` is complete.  Defaults to
            ``crop_w - 1`` (collect all columns).

    Returns:
        List of ``x_stop - x_start + 1`` run lists.  Index ``i`` in the
        returned list corresponds to column ``x_start + i``.  Each list
        sums to ``crop_h``.

    Examples:
        ```pycon
        >>> import numpy as np
        >>> from supervision.detection.compact_mask import _rle_split_cols
        >>> from supervision.detection.utils.converters import _mask_to_rle_counts
        >>> mask = np.array([[True, False], [True, True]], dtype=bool)
        >>> rle = _mask_to_rle_counts(mask)
        >>> rle.tolist()
        [0, 2, 1, 1]
        >>> _rle_split_cols(rle, 2, 2)
        [[0, 2], [1, 1]]
        >>> _rle_split_cols(rle, 2, 2, x_start=1)
        [[1, 1]]

        ```
    Nr   c                ó   — g | ]}g ‘ŒS © r"   )Ú.0Ú_s     r   ú
<listcomp>z#_rle_split_cols.<locals>.<listcomp>~   s   € Ð:Ð:Ð: q Ð:Ð:Ð:r   r   ©ÚdtypeÚright)Úsider   éÿÿÿÿ)
ÚtolistÚrangeÚlenr   ÚcumsumÚint64r   ÚsearchsortedÚminÚappend)r   r   r   r   r   Úrle_listÚn_colsÚper_colÚstart_pixelÚcumsum_endsÚ	first_runÚcÚprefixÚcolÚrowÚrun_idxÚrun_lenÚis_trueÚ	remainingÚspace_in_colÚtakeÚ	local_cols                         r   Ú_rle_split_colsrD   ;   så  € ðv €~Ø˜!‘ˆð Ÿ*š*™,œ,€Hà�gÑ Ñ!€FØ:Ð:­E°&©M¬MÐ:Ñ:Ô:€Gð ˜FÑ"€KØ�Q‚€�3˜x™=œ=¨1Ò,Ð,Ý”i ­2¬8Ð4Ñ4Ô4ˆÝ�œ¨°[ÀwÐOÑOÔOÑPÔPˆ	Ø�˜H™œÒ%Ð%Ý˜6‘]”]ð &ð &�Ø$˜X�˜‘
�
ØˆNØ4=À²M°M•�[ ¨Q¡Ô/Ñ0Ô0Ð0Àqˆˆàˆ	Øˆà
�FÑ
€CØ
�6‰/€Cå˜¥C¨¡M¤MÑ2Ô2ð !ñ !ˆØ˜7Ô#ˆØ˜A‘+ Ò"ˆØˆ	Ø˜!Šmˆmà�VŠ|ˆ|Ø�	ØØ! C™<ˆLÝ�y ,Ñ/Ô/ˆDØ�gŠ~ˆ~Ø '™M�	Ý�w˜yÔ)Ñ*Ô*¨aÒ/Ð/Øð 5Ø 	Ô*×1Ò1°!Ñ4Ô4Ð4øð ¥# g¨iÔ&8Ñ"9Ô"9¸AÑ"=ÀÑ!BÀaÒ!GÒHÐHØ˜IÔ& rÐ*Ð*Ô*¨dÑ2Ð*Ð*Ñ*Ø Ñ%�IØ˜4‘K�CØ˜f’}�}Ø˜Ø˜q™˜ØØ˜	Ô"×)Ò)¨$Ñ/Ô/Ð/Ø˜ÑˆIØ�4‰KˆCØ�fŠ}ˆ}Ø�Ø�q‘�ð7 ˜!Šmˆmð8 �Š<ˆ<ØˆEñ õ �6‰]Œ]ð "ð "ˆØ�qŒzð 	"Ø ˜ˆG�A‰Jøà€Nr   Úcol_runsú	list[int]Úsrc_hÚrow_mapc                ó  — t          |¦  «        }|dk    rdgS t          j        |t          j        ¬¦  «        }d}t	          | ¦  «        D ]\  }}|dz  dk    ||||z   …<   ||z  }Œ||k     rd||d…<   ||         }|                     t          j        ¦  «        }	t          j        t          j        |	¦  «        ¦  «        }
t          j        t          |
¦  «        dz   t          j	        ¬¦  «        }t          j        t          |
¦  «        dz   t          j	        ¬¦  «        }d|d<   |
dz   |dd…<   |
dz   |dd…<   ||d<   ||z
   
                    ¦   «         }t          |d         ¦  «        r|                     dd¦  «         |S )uZ  Scale one column's run list to a new height using a precomputed row map.

    Each output row is mapped to a source row via ``row_map``, which
    implements nearest-neighbour resampling in the vertical direction.

    Args:
        col_runs: Per-column run list starting with a ``False``-run count.
        src_h: Height of the source column (sum of ``col_runs``).
        row_map: int32 array of length ``new_crop_h``; ``row_map[r']`` is the
            source row index for output row ``r'``.  Use
            ``(np.arange(new_crop_h) * src_h // new_crop_h)`` for
            ``cv2.INTER_NEAREST``-compatible mapping.

    Returns:
        Scaled run list of total length ``len(row_map)``, always starting
        with a ``False``-run count.

    Examples:
        ```pycon
        >>> import numpy as np
        >>> from supervision.detection.compact_mask import _rle_scale_col
        >>> col_runs = [0, 2, 2]   # F=0, T=2, F=2  â†’ [T, T, F, F]
        >>> row_map = np.array([0, 1, 2, 3, 0, 1, 2, 3], dtype=np.int32)
        >>> _rle_scale_col(col_runs, 4, row_map)
        [0, 2, 2, 2, 2]

        ```
    r   r&   r   r   FNr*   )r-   r   ÚemptyÚbool_Ú	enumerateÚviewÚuint8ÚflatnonzeroÚdiffr/   r+   ÚboolÚinsert)rE   rG   rH   Ú
new_crop_hÚ
src_valuesÚposÚriÚrlÚ
out_valuesÚ	out_uint8Ú
boundariesÚ
run_startsÚrun_endsÚresult_runss                 r   Ú_rle_scale_colr^   ½   sŠ  € õB �W‘”€JØ�Q‚€Øˆsˆ
õ )+¬°½b¼hÐ(GÑ(GÔ(G€JØ
€CÝ˜HÑ%Ô%ð ð ‰ˆˆBØ%'¨!¡V¨q¢[ˆ
�3˜˜r™�>Ñ"Øˆr‰	ˆˆØ
ˆU‚{€{Ø ˆ
�3�4�4Ñð ˜GÔ$€Jð —’¥¤Ñ)Ô)€IÝ”¥¤¨	Ñ 2Ô 2Ñ3Ô3€JÝ(*¬µ°Z±´À1Ñ1DÍBÌHÐ(UÑ(UÔ(U€JÝ&(¤h­s°:©¬ÀÑ/BÍ"Ì(Ð&SÑ&SÔ&S€HØ€Jˆq�MØ !‘^€Jˆqˆrˆr�NØ ‘N€HˆSˆbˆS�MØ€HˆR�LØ&¨Ñ3×;Ò;Ñ=Ô=€KåˆJ�qŒMÑÔð !Ø×Ò˜1˜aÑ Ô Ð ØÐr   Úscaled_colsÚ	new_totalc                óø  — g }| D ]Ñ}|s|                      |¦  «         Œt          |¦  «        dz
  dz  dk    }|s4|dxx         |d         z  cc<   |                      |dd…         ¦  «         Œi|d         dk    rGt          |¦  «        dk    r4|dxx         |d         z  cc<   |                      |dd…         ¦  «         Œ¼|                      |¦  «         ŒÒt          j        |r|n|gt          j        ¬¦  «        S )a¿  Concatenate per-column run lists into a flat RLE, merging junctions.

    Each column run list starts with a ``False``-run count. Two junction types
    can be merged across column boundaries:

    * ``False``/``False``: the trailing False run merges with the leading False
      run of the next column (leading count may be zero).
    * ``True``/``True``: when the accumulated output ends on a True run and the
      next column's leading False count is zero (column starts with True), the
      two True runs are merged to avoid inserting a zero-length False run that
      would inflate ``len(rle)`` and skew the density metric in
      :func:`_resize_crop`.

    Args:
        scaled_cols: List of per-column run lists, each starting with a
            ``False``-run count.
        new_total: Total pixel count of the output (fallback for empty input).

    Returns:
        Flat int32 RLE array starting with a ``False``-run count.

    Examples:
        ```pycon
        >>> import numpy as np
        >>> from supervision.detection.compact_mask import _rle_join_cols
        >>> cols = [[1, 2], [1, 2]]  # each col: F=1, T=2
        >>> _rle_join_cols(cols, 6).tolist()
        [1, 2, 1, 2]

        ```
    r   r   r*   r   Nr&   )Úextendr-   r   ÚarrayÚint32)r_   r`   Úoutput_runsrE   Úlast_is_trues        r   Ú_rle_join_colsrg   þ   s(  € ðF  €KØð -ð -ˆØð 	-Ø×Ò˜xÑ(Ô(Ð(Ð(å Ñ,Ô,¨qÑ0°AÑ5¸Ò:ˆLàð 	-Ø˜B��” 8¨A¤;Ñ.��‘Ø×"Ò" 8¨A¨B¨B¤<Ñ0Ô0Ð0Ð0Ø˜!” Ò!Ð!¥c¨(¡m¤m°aÒ&7Ð&7ð ˜B��” 8¨A¤;Ñ.��‘Ø×"Ò" 8¨A¨B¨B¤<Ñ0Ô0Ð0Ð0à×"Ò" 8Ñ,Ô,Ð,Ð,åŒ8 ;Ð?�K�K°Y°KÅrÄxÐPÑPÔPÐPr   úSequence[int]Úy1Úy2c                ó,  — ||z
  dz   }g }d}t          | ¦  «        D ]o\  }}|dz  dk    }|}	|t          |¦  «        z   }
|
}t          |	|¦  «        }t          |
|dz   ¦  «        }||k    r|                     |||z
  f¦  «         ||k    r nŒp|s|gS g }|d         d         r|                     d¦  «         |D ][\  }}t          |¦  «        ot          |¦  «        dz
  dz  dk    }|r||k    r|dxx         |z  cc<   ŒF|                     |¦  «         Œ\|S )u¼  Restrict one full-height column RLE to inclusive rows ``[y1, y2]``.

    Args:
        col_runs: Run lengths for one full-height column, starting with a
            ``False`` run.
        y1: Inclusive top row of the crop.
        y2: Inclusive bottom row of the crop.

    Returns:
        Run lengths for the cropped column, also starting with a ``False`` run.

    Examples:
        ```pycon
        >>> from supervision.detection.compact_mask import _rle_trim_col_runs
        >>> # Full column F=2, T=2, F=2 (height 6); crop to rows 1..4 inclusive
        >>> # yields rows [F, T, T, F] â†’ F=1, T=2, F=1.
        >>> _rle_trim_col_runs([2, 2, 2], y1=1, y2=4)
        [1, 2, 1]

        ```
    r   r   r   r*   )rL   r   Úmaxr1   r2   rQ   r-   )rE   ri   rj   Útarget_heightÚ	collectedr<   r=   r>   r?   ÚstartÚendÚ
crop_startÚcrop_endÚresultÚlengthrf   s                   r   Ú_rle_trim_col_runsru   6  sq  € ð, ˜‘G˜a‘K€Mð )+€IØ
€CÝ% hÑ/Ô/ð ð Ñˆ�Ø˜A‘+ Ò"ˆØˆØ•C˜‘L”LÑ ˆØˆå˜ ‘^”^ˆ
Ý�s˜B ™FÑ#Ô#ˆØ�jÒ Ð Ø×Ò˜g x°*Ñ'<Ð=Ñ>Ô>Ð>Ø�Š8ˆ8ØˆEð ð ð ØˆÐà€FØ�„|�A„ð Ø�Š�aÑÔÐØ$ð "ð "‰ˆ�Ý˜F‘|”|ÐB­¨V©¬°q©¸AÑ(=ÀÒ(BˆØð 	"�l gÒ-Ð-Ø�2ˆJˆJŒJ˜&Ñ ˆJˆJ‰JˆJà�MŠM˜&Ñ!Ô!Ð!Ð!Ø€Mr   Úcountsr   c                óp  — 	 t          | t          ¦  «        r|                      d¦  «        } t          | t          ¦  «        r=t	          t          | ¦  «        ¦  «        }t          j        |t          j        ¬¦  «        }n­t          j	        | t          j
        ¬¦  «        }t          j        t          j        ¦  «        }|j        rI|                     ¦   «         |j        k    s|                     ¦   «         |j        k     rt          d¦  «        ‚|                     t          j        ¦  «        }n/# t"          t          t$          f$ r}t          d¦  «        |‚d}~ww xY w|j        dk    rt          d¦  «        ‚|j        dk    rt          d	¦  «        ‚t          j        |dk     ¦  «        rt          d
¦  «        ‚|S )aB  Decode COCO RLE counts into absolute F-order run lengths.

    Args:
        counts: COCO compressed counts (``str`` or ``bytes``), or uncompressed
            integer run lengths.

    Returns:
        One-dimensional ``int32`` run-length array.

    Raises:
        ValueError: If counts cannot be decoded into non-negative run lengths.

    Examples:
        ```pycon
        >>> from supervision.detection.compact_mask import _coco_rle_counts_to_array
        >>> _coco_rle_counts_to_array([0, 2, 2, 2, 10])
        array([ 0,  2,  2,  2, 10], dtype=int32)

        ```
    zutf-8r&   z#COCO RLE counts exceed int32 range.zInvalid COCO RLE counts.Nr   z(COCO RLE counts must be one-dimensional.r   z COCO RLE counts cannot be empty.z%COCO RLE counts must be non-negative.)Ú
isinstanceÚbytesÚdecodeÚstrr   r
   r   rc   rd   Úasarrayr/   ÚiinfoÚsizerl   r1   Ú
ValueErrorÚastypeÚ	TypeErrorÚOverflowErrorÚndimÚany)rv   Údecoded_countsÚ
counts_arrÚcounts_arr64Ú
int32_infoÚexcs         r   Ú_coco_rle_counts_to_arrayrŠ   n  s’  € ð*>Ý�f�eÑ$Ô$ð 	,Ø—]’] 7Ñ+Ô+ˆFÝ�f�cÑ"Ô"ð 	7Ý*­>¸&Ñ+AÔ+AÑBÔBˆNÝœ .½¼ÐAÑAÔAˆJˆJõ
 œ: fµB´HÐ=Ñ=Ô=ˆLÝœ¥"¤(Ñ+Ô+ˆJØÔ ð HØ× Ò Ñ"Ô" Z¤^Ò3Ð3Ø×#Ò#Ñ%Ô%¨
¬Ò6Ð6å Ð!FÑGÔGÐGØ%×,Ò,­R¬XÑ6Ô6ˆJøøÝ•z¥=Ð1ð >ð >ð >ÝÐ3Ñ4Ô4¸#Ð=øøøøð>øøøð „˜!ÒÐÝÐCÑDÔDÐDØ„˜!ÒÐÝÐ;Ñ<Ô<Ð<Ý	„vˆj˜1ŠnÑÔð BÝÐ@ÑAÔAÐAØÐs   ‚D)D, Ä,EÅEÅErS   Ú
new_crop_wc                ór  — ||z  }||z  dk    s|dk    r!t          j        dgt           j        ¬¦  «        S t          | ¦  «        dk    s.t	          t          j        | ddd…         ¦  «        ¦  «        dk    r!t          j        |gt           j        ¬¦  «        S t          | ¦  «        dk    r.| d         dk    r"t          j        d|gt           j        ¬¦  «        S t          | ||¦  «        }t          j        |¦  «        |z  |z                       t           j        ¦  «        }t          j        |¦  «        |z  |z                       t           j        ¦  «        }i }	g }
|D ]J}t	          |¦  «        }||	vrt          ||         ||¦  «        |	|<   |
 
                    |	|         ¦  «         ŒKt          |
|¦  «        S )a   Resize an F-order RLE-encoded crop via nearest-neighbour resampling.

    Manipulates run lengths directly without decoding to a full 2D boolean
    array.  Delegates to :func:`_rle_split_cols`, :func:`_rle_scale_col`,
    and :func:`_rle_join_cols`.

    The nearest-neighbour mapping ``src = floor(dst * src_size / dst_size)``
    is bit-exact with ``cv2.INTER_NEAREST``.

    Args:
        rle: int32 array of F-order run lengths as produced by
            :func:`~supervision.detection.utils.converters._mask_to_rle_counts`.
            Starts with a ``False``-run count (may be 0).
        crop_h: Height of the original crop.
        crop_w: Width of the original crop.
        new_crop_h: Height of the resized crop.
        new_crop_w: Width of the resized crop.

    Returns:
        int32 array of F-order run lengths for the resized crop, starting
        with the ``False``-run count.

    Examples:
        Upscale a 3x3 mask with a diagonal True stripe to 6x6:

        ```pycon
        >>> import numpy as np
        >>> from supervision.detection.compact_mask import _rle_resize
        >>> from supervision.detection.utils.converters import (
        ...     _mask_to_rle_counts, _rle_counts_to_mask,
        ... )
        >>> mask = np.array([
        ...     [True,  False, False],
        ...     [False, True,  False],
        ...     [False, False, True ],
        ... ], dtype=bool)
        >>> rle = _mask_to_rle_counts(mask)
        >>> resized_rle = _rle_resize(rle, 3, 3, 6, 6)
        >>> result = _rle_counts_to_mask(resized_rle, 6, 6)
        >>> result.astype(int)
        array([[1, 1, 0, 0, 0, 0],
               [1, 1, 0, 0, 0, 0],
               [0, 0, 1, 1, 0, 0],
               [0, 0, 1, 1, 0, 0],
               [0, 0, 0, 0, 1, 1],
               [0, 0, 0, 0, 1, 1]])

        ```
    r   r&   r   Nr   )r   rc   rd   r-   r   r   rD   Úaranger€   r^   r2   rg   )r   r   r   rS   r‹   r`   r5   Úcol_maprH   Ú	col_cacher_   Úsrc_cÚsrc_cols                r   Ú_rle_resizer’   ¡  s¢  € ðp ˜ZÑ'€Ià��˜!ÒÐ˜y¨Aš~˜~ÝŒx˜˜¥2¤8Ð,Ñ,Ô,Ð,Ý
ˆ3�x„x�1‚}€}��BœF 3 q t¨! t¤9Ñ-Ô-Ñ.Ô.°!Ò3Ð3ÝŒx˜˜­2¬8Ð4Ñ4Ô4Ð4Ý
ˆ3�x„x�1‚}€}˜˜Qœ 1š˜ÝŒx˜˜I˜­b¬hÐ7Ñ7Ô7Ð7å˜c 6¨6Ñ2Ô2€Gõ Œy˜Ñ$Ô$ vÑ-°Ñ;×CÒCÅBÄHÑMÔM€Gõ Œy˜Ñ$Ô$ vÑ-°Ñ;×CÒCÅBÄHÑMÔM€Gð ')€IØ€KØð /ð /ˆÝ�e‘*”*ˆØ˜)Ð#Ð#Ý!/°¸Ô0@À&È'Ñ!RÔ!RˆI�gÑØ×Ò˜9 WÔ-Ñ.Ô.Ð.Ð.å˜+ yÑ1Ô1Ð1r   g      Ð?ÚfloatÚ_L3_DENSITY_THRESHOLDé   Ú_PARALLEL_THRESHOLDi €  Ú_MAX_IMAGE_DIMENSIONi @  Ú_SMALL_IMAGE_DENSE_THRESHOLDÚorig_hÚorig_wÚnew_hÚnew_wc                óâ  — ddl m} t          | ¦  «        dk    r$t          j        ||z  gt          j        ¬¦  «        S t          | ¦  «        t          d||z  ¦  «        z  t          k     rt          | ||||¦  «        S t          | ||¦  «        }|                     |                     t          j        ¦  «        ||f|j        ¬¦  «                             t           ¦  «        }t#          |¦  «        S )uß  Resize one RLE crop to ``(new_h, new_w)``, choosing the fastest path.

    Dispatch order:

    1. **All-False fast path** â€” returns a single False run; no decode.
    2. **L3 direct RLE path** â€” used when run density is below
       :data:`_L3_DENSITY_THRESHOLD`; manipulates run lengths without
       allocating a 2D array.
    3. **cv2 fallback** â€” decodes to ``uint8``, calls
       ``cv2.resize(INTER_NEAREST)``, re-encodes; used for dense masks.

    Args:
        rle: int32 run-length array for the source crop.
        orig_h: Height of the source crop.
        orig_w: Width of the source crop.
        new_h: Target height.
        new_w: Target width.

    Returns:
        int32 RLE array for the resized crop.
    r   )Ú_cv2r&   r   )Úinterpolation)Úsupervisionrž   r   r   rc   rd   r-   rl   r”   r’   r   ÚresizerM   rN   ÚINTER_NEARESTr€   rQ   r   )r   r™   rš   r›   rœ   Úcv2ÚcropÚresizeds           r   Ú_resize_cropr¦     sì   € ð8 (Ð'Ð'Ð'Ð'Ð'õ ��~„~˜ÒÐÝŒx˜ ™˜­r¬xÐ8Ñ8Ô8Ð8õ ˆ3�x„x•#�a˜ &™Ñ)Ô)Ñ)Õ,AÒAÐAÝ˜3 ¨°°uÑ=Ô=Ð=õ ˜s F¨FÑ3Ô3€DØ�jŠjØ�	Š	•"”(ÑÔØ	�ˆØÔ'ð ñ ô ÷ ‚f�T�l„lð	 õ
 ˜wÑ'Ô'Ð'r   c                  ó†  — e Zd ZdZdZdBd„ZedCd„¦   «         ZedDd„¦   «         ZdEd„Z	dFd„Z
dGd„ZdHd„ZedId„¦   «         ZedJd„¦   «         ZedKd„¦   «         ZedKd „¦   «         ZedLd"„¦   «         ZedMd$„¦   «         Z	 dNdOd)„ZedPd+„¦   «         ZedQd-„¦   «         ZdRd0„Z	 dNdSd4„ZdTd8„ZedUd;„¦   «         ZdVd<„ZdWd@„ZdXdA„Zd%S )YÚCompactMaskuÎ  Memory-efficient crop-RLE mask storage for instance segmentation.

    Instead of storing N full ``(H, W)`` boolean arrays, :class:`CompactMask`
    encodes each mask as a run-length sequence of its bounding-box crop.  This
    reduces memory from O(NÂ·HÂ·W) to roughly O(NÂ·bbox_area), which is orders of
    magnitude smaller for sparse masks on high-resolution images.

    The class exposes a duck-typed interface compatible with ``np.ndarray``
    masks used elsewhere in ``supervision``:

    * ``mask[int]`` â†’ dense ``(H, W)`` bool array (annotators, converters).
    * ``mask[slice | list | ndarray]`` â†’ new :class:`CompactMask` (filtering).
    * ``np.asarray(mask)`` â†’ dense ``(N, H, W)`` bool array (numpy interop).
    * ``mask.shape``, ``mask.dtype``, ``mask.area`` â€” match the dense API.

    :class:`CompactMask` is **not** a drop-in ``np.ndarray`` replacement.
    When you need to call arbitrary ndarray methods (``astype``, ``reshape``,
    ``ravel``, ``any``, ``all``, â€¦) call :meth:`to_dense` first:
    ``cm.to_dense().astype(np.uint8)``.  :meth:`to_dense` is the single
    explicit materialisation boundary.

    .. note:: **RLE encoding â€” COCO / pycocotools pixel-scan order**

        :class:`CompactMask` uses **column-major (Fortran-order, F-order)**
        run-lengths scoped to each mask's bounding-box crop, matching the
        pixel-scan order used by the COCO API (pycocotools).  The crop scope
        still differs from the full-image scope used by pycocotools, so a
        :class:`CompactMask` RLE cannot be passed directly to
        ``maskUtils.iou()`` or ``maskUtils.decode()`` without re-scoping to
        the full canvas.  Use :meth:`to_dense` to obtain a standard boolean
        array for pycocotools interop.

        This scan order is part of CompactMask's internal RLE representation.
        Switching from row-major (C-order) to column-major (F-order) is a
        backward-incompatible format change for any persisted or serialized
        :class:`CompactMask` state, including pickled objects and any
        external storage of ``._rles``.  Older stored RLE arrays will decode
        incorrectly under the new convention.

        Migration note: load or decode legacy masks with the older version,
        materialize them to dense boolean arrays, and then re-encode them
        with the current version (for example via :meth:`to_dense` followed
        by :meth:`from_dense`) before persisting them again.

    Args:
        rles: List of N int32 run-length arrays.
        crop_shapes: Array of shape ``(N, 2)`` â€” ``(crop_h, crop_w)`` per mask.
        offsets: Array of shape ``(N, 2)`` â€” ``(x1, y1)`` bounding-box origins.
        image_shape: ``(H, W)`` of the full image.

    Examples:
        ```pycon
        >>> import numpy as np
        >>> from supervision.detection.compact_mask import CompactMask
        >>> masks = np.zeros((2, 100, 100), dtype=bool)
        >>> masks[0, 10:20, 10:20] = True
        >>> masks[1, 50:70, 50:80] = True
        >>> xyxy = np.array([[10, 10, 19, 19], [50, 50, 79, 69]], dtype=np.float32)
        >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(100, 100))
        >>> len(cm)
        2
        >>> cm.shape
        (2, 100, 100)

        ```
    )Ú_crop_shapesÚ_image_shapeÚ_offsetsÚ_rlesÚrlesúlist[npt.NDArray[np.int32]]Úcrop_shapesr   ÚoffsetsÚimage_shapeútuple[int, int]r   ÚNonec                ó>   — || _         || _        || _        || _        d S ©N)r¬   r©   r«   rª   )Úselfr­   r¯   r°   r±   s        r   Ú__init__zCompactMask.__init__{  s(   € ð 37ˆŒ
Ø3>ˆÔØ/6ˆŒØ-8ˆÔÐÐr   Úmasksúnpt.NDArray[np.bool_]Úxyxyúnpt.NDArray[np.number]c                ó  — |\  }}t          |¦  «        }|dk    rJ | g t          j        dt          j        ¬¦  «        t          j        dt          j        ¬¦  «        |¦  «        S g }g }g }	t	          |¦  «        D �]À}
||
         \  }}}}t          |¦  «        t          |¦  «        t          |¦  «        t          |¦  «        f\  }}}}t          t          dt          ||dz
  ¦  «        ¦  «        ¦  «        }t          t          dt          ||dz
  ¦  «        ¦  «        ¦  «        }||k     s||k     s|dk     s|dk     s||k    s||k    r t          j        dt          ¬¦  «        }d}d}n�t          t          dt          ||dz
  ¦  «        ¦  «        ¦  «        }t          t          dt          ||dz
  ¦  «        ¦  «        ¦  «        }||
||dz   …||dz   …f         }||z
  dz   }||z
  dz   }| 
                    t          |¦  «        ¦  «         | 
                    ||f¦  «         |	 
                    ||f¦  «         �ŒÂt          j        |t          j        ¬¦  «        }t          j        |	t          j        ¬¦  «        } | ||||¦  «        S )at  Create a :class:`CompactMask` from a dense ``(N, H, W)`` bool array.

        Bounding boxes are clipped to image bounds and interpreted in the
        supervision ``xyxy`` convention (inclusive max coordinates). A
        box with invalid ordering (``x2 < x1`` or ``y2 < y1``) is replaced by
        a ``1x1`` all-False crop to avoid degenerate RLE.

        Args:
            masks: Dense boolean mask array of shape ``(N, H, W)``.
            xyxy: Bounding boxes of shape ``(N, 4)`` in ``[x1, y1, x2, y2]``
                format.
            image_shape: ``(H, W)`` of the full image.

        Returns:
            A new :class:`CompactMask` instance.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> from supervision.detection.compact_mask import CompactMask
            >>> masks = np.zeros((1, 100, 100), dtype=bool)
            >>> masks[0, 10:20, 10:20] = True
            >>> xyxy = np.array([[10, 10, 19, 19]], dtype=np.float32)
            >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(100, 100))
            >>> cm.shape
            (1, 100, 100)

            ```
        r   ©r   r   r&   r   ©r   r   )r-   r   rJ   rd   r,   r   rl   r1   ÚzerosrQ   r2   r   rc   )Úclsr¸   rº   r±   Úimg_hÚimg_wÚ	num_masksr­   Úcrop_shapes_listÚoffsets_listÚmask_idxÚx1ri   Úx2rj   Úx1iÚy1iÚx2iÚy2iÚx1cÚy1cr¤   r   r   Úx2cÚy2cr¯   r°   s                               r   Ú
from_densezCompactMask.from_dense‹  s†  € ðH #‰ˆˆuÝ˜‘J”Jˆ	à˜Š>ˆ>Ø�3ØÝ”˜¥r¤xÐ0Ñ0Ô0Ý”˜¥r¤xÐ0Ñ0Ô0Øñ	ô ð ð -/ˆØ24ÐØ.0ˆå˜iÑ(Ô(ð 	,ñ 	,ˆHØ! (œ^‰NˆB��B˜Ý!$ R¡¤­#¨b©'¬'µ3°r±7´7½CÀ¹G¼GÐ!CÑˆC��c˜3Ý•c˜!�S  e¨a¡iÑ0Ô0Ñ1Ô1Ñ2Ô2ˆCÝ•c˜!�S  e¨a¡iÑ0Ô0Ñ1Ô1Ñ2Ô2ˆCð
 �c’	�	Ø˜’9�9Ø˜’7�7Ø˜’7�7Ø˜%’<�<Ø˜%’<�<å”x ­dÐ3Ñ3Ô3�Ø�Ø��å�#˜a¥ S¨%°!©)Ñ!4Ô!4Ñ5Ô5Ñ6Ô6�Ý�#˜a¥ S¨%°!©)Ñ!4Ô!4Ñ5Ô5Ñ6Ô6�Ø˜X s¨S°1©W }°c¸CÀ!¹G°mÐCÔD�Ø˜s™ Q™�Ø˜s™ Q™�Ø�KŠKÕ+¨DÑ1Ô1Ñ2Ô2Ð2Ø×#Ò# V¨VÐ$4Ñ5Ô5Ð5Ø×Ò  c 
Ñ+Ô+Ð+Ñ+å”hÐ/µr´xÐ@Ñ@Ô@ˆÝ”(˜<­r¬xÐ8Ñ8Ô8ˆØˆs�4˜ g¨{Ñ;Ô;Ð;r   úSequence[Mapping[str, Any]]únpt.NDArray[np.floating]c           	     ó`  ‡+‡,— t          |d         ¦  «        t          |d         ¦  «        }}|dk    s|dk    rt          d¦  «        ‚|t          k    s|t          k    rt          d||f› dt          › d�¦  «        ‚t          j        |¦  «        }|j        t          |¦  «        dfk    rt          d¦  «        ‚t          |¦  «        dk    rL | g t          j        d	t          j        ¬
¦  «        t          j        d	t          j        ¬
¦  «        ||f¦  «        S g }g }g }	t          |¦  «        D �]2\  }
}t          |t          ¦  «        st          d¦  «        ‚d|vsd|vrt          d¦  «        ‚	 |d         \  }}t          |¦  «        }t          |¦  «        }n)# t          t          f$ r}t          d¦  «        |‚d}~ww xY w||f||fk    rt          d||f› d||f› d�¦  «        ‚t          |d         ¦  «        }t          t          j        |t          j        ¬
¦  «        ¦  «        ||z  k    rt          d¦  «        ‚||
         \  }}}}t          |¦  «        t          |¦  «        t          |¦  «        t          |¦  «        f\  }}}}t!          dt#          ||dz
  ¦  «        ¦  «        }t!          dt#          ||dz
  ¦  «        ¦  «        Š+||k     s||k     s|dk     s|dk     s||k    s||k    rb|                     t          j        dgt          j        ¬
¦  «        ¦  «         |                     d¦  «         |	                     |‰+f¦  «         �Œ%t!          dt#          ||dz
  ¦  «        ¦  «        }t!          dt#          ||dz
  ¦  «        ¦  «        Š,‰,‰+z
  dz   }||z
  dz   }||z  t(          k    �r3t          j        |t          j        ¬
¦  «        }||                     t          j        ¦  «        z
  }|ddd…         }|ddd…         }|j        dk    r®t          j        ||z  dz   t          j        ¬
¦  «        } t          j                             | |d¦  «         t          j                             | |d¦  «         t          j        | dd…         t          j        ¬
¦  «                             t          j        ¦  «        }!n#t          j        ||z  t          j        ¬
¦  «        }!|!                     ||¦  «        ||dz   …‰+‰,dz   …f                              ¦   «         }"t          j        t          j        |"                      t          j!        ¦  «        ¦  «        ¦  «        d         dz   }#t          j"        dg|#t          |"¦  «        gg¦  «        }$t          j        |$¦  «        }%|"d         rt          j"        dg|%g¦  «        }%|%                     t          j        ¦  «        }&n6tG          |||||¬¦  «        }'ˆ+ˆ,fd„|'D ¦   «         }(tI          |(||z  ¦  «        }&|                     |&¦  «         |                     ||f¦  «         |	                     |‰+f¦  «         �Œ4t          j        |t          j        ¬
¦  «        })t          j        |	t          j        ¬
¦  «        }* | ||)|*||f¦  «        S )a  Create a :class:`CompactMask` from full-frame COCO RLE masks.

        Transcodes full-image COCO RLE payloads into the crop-scoped RLE format
        used by :class:`CompactMask`. The conversion uses run-length arithmetic
        scoped by ``xyxy`` boxes and does not materialise a dense ``(N, H, W)``
        mask stack.

        Args:
            rles: Sequence of COCO RLE dictionaries. Each dictionary must contain
                ``"size"`` as ``[height, width]`` and ``"counts"`` as compressed
                counts (``str`` or ``bytes``) or uncompressed integer run lengths.
            xyxy: Bounding boxes of shape ``(N, 4)`` in ``[x1, y1, x2, y2]``
                format. Max coordinates follow supervision's inclusive convention.
            image_shape: ``(H, W)`` of the full image. This must match every RLE
                ``"size"`` value.

        Returns:
            A new :class:`CompactMask` instance.

        Raises:
            ValueError: If the RLE payloads are malformed, are not aligned with
                ``xyxy``, or their sizes/counts do not match ``image_shape``.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> from supervision.detection.compact_mask import CompactMask
            >>> # 4x4 image with a 2x2 True block at the top-left corner.
            >>> # Uncompressed F-order COCO counts: F=0, T=2, F=2, T=2, F=10
            >>> # (column-major: col0=[T,T,F,F], col1=[T,T,F,F], cols2-3 all F).
            >>> rles = [{"size": [4, 4], "counts": [0, 2, 2, 2, 10]}]
            >>> xyxy = np.array([[0, 0, 3, 3]], dtype=np.float32)
            >>> cm = CompactMask.from_coco_rle(rles, xyxy, image_shape=(4, 4))
            >>> cm.shape
            (1, 4, 4)
            >>> cm.area.tolist()
            [4]

            ```
        r   r   z3image_shape must contain positive height and width.zimage_shape z* exceeds the maximum allowed dimension of z pixels per side.é   z@xyxy must have shape (N, 4), where N matches the number of RLEs.r½   r&   z#Each RLE payload must be a mapping.r~   rv   z2Each RLE payload must contain 'size' and 'counts'.z!RLE size must be [height, width].Nz	RLE size z must match image_shape ú.z5The sum of COCO RLE counts must match the image area.r¾   r   r*   )r   r   c                ó2   •— g | ]}t          |‰‰¦  «        ‘ŒS r"   )ru   )r#   r;   rÎ   rÐ   s     €€r   r%   z-CompactMask.from_coco_rle.<locals>.<listcomp>x  s&   ø€ Ð#VÐ#VÐ#VÈ#Õ$6°s¸CÀÑ$EÔ$EÐ#VÐ#VÐ#Vr   )%r   r   r—   r   r|   Úshaper-   rJ   rd   rL   rx   r   r�   rŠ   r   r/   rl   r1   r2   rc   r˜   r.   r€   r~   r¿   ÚaddÚatrN   ÚreshapeÚravelÚwhererP   rM   Úint8ÚconcatenaterD   rg   )-rÀ   r­   rº   r±   rÁ   rÂ   Úxyxy_arrÚ	crop_rlesrÄ   rÅ   rÆ   r   Úrle_hÚrle_wr‰   rv   rÇ   ri   rÈ   rj   rÉ   rÊ   rË   rÌ   rÍ   rÏ   r   r   ÚendsÚstartsÚtrue_startsÚ	true_endsÚ	indicatorÚflatÚ	flat_cropÚ
change_posrZ   Úrun_lensÚcrop_rle_arrÚcolsÚselected_columnsr¯   r°   rÎ   rÐ   s-                                              @@r   Úfrom_coco_rlezCompactMask.from_coco_rleß  s¸  øø€ õ^ ˜K¨œNÑ+Ô+­S°¸Q´Ñ-@Ô-@ˆuˆØ�AŠ:ˆ:˜ !š˜ÝÐRÑSÔSÐSØÕ'Ò'Ð'¨5Õ3GÒ+GÐ+GÝð>  u˜~ð >ð >Ý*ð>ð >ð >ñô ð õ
 ”:˜dÑ#Ô#ˆØŒ>�c $™iœi¨˜^Ò+Ð+ÝØRñô ð õ ˆt‰9Œ9˜Š>ˆ>Ø�3ØÝ”˜¥r¤xÐ0Ñ0Ô0Ý”˜¥r¤xÐ0Ñ0Ô0Ø˜�ñ	ô ð ð 24ˆ	Ø24ÐØ.0ˆå& t™_œ_ð T	,ñ T	,‰MˆH�cÝ˜c¥7Ñ+Ô+ð HÝ Ð!FÑGÔGÐGØ˜SÐ Ð  H°CÐ$7Ð$7Ý Ð!UÑVÔVÐVðOà" 6œ{‘��uÝ˜E™
œ
�Ý˜E™
œ
��øÝ�zÐ*ð Oð Oð OÝ Ð!DÑEÔEÈ3ÐNøøøøðOøøøð �uˆ~ %¨ Ò/Ð/Ý ð) ¨ ð )ð )Ø˜u�~ð)ð )ð )ñô ð õ
 /¨s°8¬}Ñ=Ô=ˆFÝ•2”6˜&­¬Ð1Ñ1Ô1Ñ2Ô2°e¸e±mÒCÐCÝ ØKñô ð ð & hÔ/‰NˆB��B˜Ý!$ R¡¤­#¨b©'¬'µ3°r±7´7½CÀ¹G¼GÐ!CÑˆC��c˜3Ý�a�˜S %¨!¡)Ñ,Ô,Ñ-Ô-ˆCÝ�a�˜S %¨!¡)Ñ,Ô,Ñ-Ô-ˆCð �c’	�	Ø˜’9�9Ø˜’7�7Ø˜’7�7Ø˜%’<�<Ø˜%’<�<à× Ò ¥¤¨1¨#µR´XÐ!>Ñ!>Ô!>Ñ?Ô?Ð?Ø ×'Ò'¨Ñ/Ô/Ð/Ø×#Ò# S¨# JÑ/Ô/Ð/Ùå�a�˜S %¨!¡)Ñ,Ô,Ñ-Ô-ˆCÝ�a�˜S %¨!¡)Ñ,Ô,Ñ-Ô-ˆCØ˜3‘Y ‘]ˆFØ˜3‘Y ‘]ˆFà�u‰}Õ <Ò<Ñ<õ ”y ­r¬xÐ8Ñ8Ô8�Ø §¢­b¬hÑ 7Ô 7Ñ7�à$ Q T¨ Tœl�Ø    A œJ�	ØÔ# aÒ'Ð'Ý "¤¨°©¸Ñ):Å"Ä(Ð KÑ KÔ K�IÝ”F—I’I˜i¨°aÑ8Ô8Ð8Ý”F—I’I˜i¨°BÑ7Ô7Ð7åœ9 Y¨s°¨s¤^½2¼8ÐDÑDÔD×KÒKÍBÌHÑUÔU�D�Dåœ8 E¨E¡M½¼ÐBÑBÔB�Dà ŸLšL¨°Ñ6Ô6Ø˜# ™'�M 3¨¨q© =Ð0ôç’%‘'”'ð õ  œX¥b¤g¨i¯nªn½R¼WÑ.EÔ.EÑ&FÔ&FÑGÔGÈÔJÈQÑN�
Ýœ^¨a¨S°*½sÀ9¹~¼~Ð>NÐ,OÑPÔP�
Ýœ7 :Ñ.Ô.�Ø˜Q”<ð ?Ý!œ~°¨s°H¨oÑ>Ô>�HØ'Ÿš­r¬xÑ8Ô8��å& v¨u°eÀSÐQTÐUÑUÔU�Ø#VÐ#VÐ#VÐ#VÐ#VÐQUÐ#VÑ#VÔ#VÐ Ý-Ð.>ÀÈÁÑPÔP�à×Ò˜\Ñ*Ô*Ð*Ø×#Ò# V¨VÐ$4Ñ5Ô5Ð5Ø×Ò  c 
Ñ+Ô+Ð+Ñ+å”hÐ/µr´xÐ@Ñ@Ô@ˆÝ”(˜<­r¬xÐ8Ñ8Ô8ˆØˆs�9˜k¨7°U¸E°NÑCÔCÐCs   Å.)FÆF>Æ)F9Æ9F>c                óÞ  — t          | j        ¦  «        }| j        \  }}t          j        |||ft
          ¬¦  «        }t          |¦  «        D ] }t          | j        |df         ¦  «        t          | j        |df         ¦  «        }}t          | j	        |df         ¦  «        t          | j	        |df         ¦  «        }	}t          | j        |         ||¦  «        }
|
|||	|	|z   …|||z   …f<   Œ¡|S )aj  Materialise all masks as a dense ``(N, H, W)`` boolean array.

        Returns:
            Boolean array of shape ``(N, H, W)``.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> from supervision.detection.compact_mask import CompactMask
            >>> masks = np.zeros((1, 50, 50), dtype=bool)
            >>> masks[0, 10:20, 10:30] = True
            >>> xyxy = np.array([[10, 10, 29, 19]], dtype=np.float32)
            >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(50, 50))
            >>> cm.to_dense().shape
            (1, 50, 50)

            ```
        r&   r   r   )r-   r¬   rª   r   r¿   rQ   r,   r   r©   r«   r   )r¶   rÃ   rÁ   rÂ   rs   rÆ   r   r   rÇ   ri   r¤   s              r   Úto_densezCompactMask.to_dense‡  sü   € õ& ˜œ
‘O”Oˆ	ØÔ(‰ˆˆuÝ(*¬°)¸UÀEÐ1JÕRVÐ(WÑ(WÔ(WˆÝ˜iÑ(Ô(ð 	Hð 	HˆHå�DÔ% h° kÔ2Ñ3Ô3Ý�DÔ% h° kÔ2Ñ3Ô3ð ˆFõ ˜œ x° {Ô3Ñ4Ô4µc¸$¼-ÈÐRSÈÔ:TÑ6UÔ6U�ˆBÝ& t¤z°(Ô';¸VÀVÑLÔLˆDØCGˆF�8˜R " v¡+Ð-¨r°B¸±KÐ/?Ð?Ñ@Ð@Øˆr   Úindexr   c                óª   — t          | j        |df         ¦  «        }t          | j        |df         ¦  «        }t          | j        |         ||¦  «        S )u"  Decode a single mask crop without allocating the full image array.

        This is an O(crop_area) operation â€” ideal for annotators that only
        need the cropped region.

        Args:
            index: Index of the mask to decode.

        Returns:
            Boolean array of shape ``(crop_h, crop_w)``.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> from supervision.detection.compact_mask import CompactMask
            >>> masks = np.zeros((1, 100, 100), dtype=bool)
            >>> masks[0, 20:30, 10:40] = True
            >>> xyxy = np.array([[10, 20, 39, 29]], dtype=np.float32)
            >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(100, 100))
            >>> cm.crop(0).shape
            (10, 30)

            ```
        r   r   )r   r©   r   r¬   )r¶   ró   r   r   s       r   r¤   zCompactMask.crop§  sO   € õ2 �TÔ& u¨a xÔ0Ñ1Ô1ˆÝ�TÔ& u¨a xÔ0Ñ1Ô1ˆÝ" 4¤:¨eÔ#4°f¸fÑEÔEÐEr   c                ó*   — t          | j        ¦  «        S )aÀ  Return the number of masks.

        Returns:
            Number of masks N.

        Examples:
            ```pycon
            >>> from supervision.detection.compact_mask import CompactMask
            >>> import numpy as np
            >>> cm = CompactMask(
            ...     [], np.empty((0, 2), dtype=np.int32),
            ...     np.empty((0, 2), dtype=np.int32), (100, 100))
            >>> len(cm)
            0

            ```
        )r-   r¬   ©r¶   s    r   Ú__len__zCompactMask.__len__È  s   € õ$ �4”:‰ŒÐr   úIterator[npt.NDArray[np.bool_]]c              #  ó\   K  — t          t          | ¦  «        ¦  «        D ]}| |         V — ŒdS )z6Iterate over masks as dense ``(H, W)`` boolean arrays.N)r,   r-   )r¶   rÆ   s     r   Ú__iter__zCompactMask.__iter__Ü  s@   è è € å�c $™iœiÑ(Ô(ð 	!ð 	!ˆHØ�x”.Ð Ð Ð Ð ð	!ð 	!r   útuple[int, int, int]c                ó:   — | j         \  }}t          | ¦  «        ||fS )aì  Return ``(N, H, W)`` matching the dense mask convention.

        Returns:
            Tuple ``(N, H, W)``.

        Examples:
            ```pycon
            >>> from supervision.detection.compact_mask import CompactMask
            >>> import numpy as np
            >>> cm = CompactMask(
            ...     [], np.empty((0, 2), dtype=np.int32),
            ...     np.empty((0, 2), dtype=np.int32), (480, 640))
            >>> cm.shape
            (0, 480, 640)

            ```
        )rª   r-   )r¶   rÁ   rÂ   s      r   rØ   zCompactMask.shapeá  s#   € ð& Ô(‰ˆˆuÝ�D‘	”	˜5 %Ð(Ð(r   c                ó   — | j         S )aï  Return ``(H, W)`` of the full image this mask is scoped to.

        Returns:
            Tuple ``(H, W)``.

        Examples:
            ```pycon
            >>> from supervision.detection.compact_mask import CompactMask
            >>> import numpy as np
            >>> cm = CompactMask(
            ...     [], np.empty((0, 2), dtype=np.int32),
            ...     np.empty((0, 2), dtype=np.int32), (480, 640))
            >>> cm.image_shape
            (480, 640)

            ```
        )rª   rö   s    r   r±   zCompactMask.image_shape÷  s   € ð& Ô Ð r   c                ó   — | j         S )ak  Return per-mask crop origins as ``(x1, y1)`` integer offsets.

        Returns:
            Array of shape ``(N, 2)`` with ``int32`` offsets.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> from supervision.detection.compact_mask import CompactMask
            >>> masks = np.zeros((1, 10, 10), dtype=bool)
            >>> masks[0, 2:4, 3:5] = True
            >>> xyxy = np.array([[3, 2, 4, 3]], dtype=np.float32)
            >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(10, 10))
            >>> cm.offsets.tolist()
            [[3, 2]]

            ```
        ©r«   rö   s    r   r°   zCompactMask.offsets  s   € ð( Œ}Ðr   c                óv  — t          | ¦  «        dk    r t          j        dt          j        ¬¦  «        S | j        dd…df         }| j        dd…df         }|| j        dd…df         z   dz
  }|| j        dd…df         z   dz
  }t          j        ||||f¦  «                             t          j        d¬¦  «        S )aü  Return per-mask inclusive bounding boxes in ``xyxy`` format.

        Boxes are derived from crop metadata:
        ``x2 = x1 + crop_w - 1``, ``y2 = y1 + crop_h - 1``.

        Returns:
            Array of shape ``(N, 4)`` with ``int32`` boxes
            ``[x1, y1, x2, y2]``.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> from supervision.detection.compact_mask import CompactMask
            >>> masks = np.zeros((1, 10, 10), dtype=bool)
            >>> masks[0, 2:5, 3:7] = True
            >>> xyxy = np.array([[3, 2, 6, 4]], dtype=np.float32)
            >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(10, 10))
            >>> cm.bbox_xyxy.tolist()
            [[3, 2, 6, 4]]

            ```
        r   )r   rÕ   r&   Nr   F©Úcopy)r-   r   rJ   rd   r«   r©   Úcolumn_stackr€   )r¶   rÇ   ri   rÈ   rj   s        r   Ú	bbox_xyxyzCompactMask.bbox_xyxy"  s¾   € õ0 ˆt‰9Œ9˜Š>ˆ>Ý”8˜F­"¬(Ð3Ñ3Ô3Ð3à$(¤M°!°!°!°Q°$Ô$7ˆØ$(¤M°!°!°!°Q°$Ô$7ˆØ$&¨Ô):¸1¸1¸1¸a¸4Ô)@Ñ$@À1Ñ$DˆØ$&¨Ô):¸1¸1¸1¸a¸4Ô)@Ñ$@À1Ñ$DˆÝŒ  B¨¨BÐ/Ñ0Ô0×7Ò7½¼ÀuÐ7ÑMÔMÐMr   únp.dtype[np.bool_]c                ó4   — t          j        t          ¦  «        S )uØ  Return ``np.dtype(bool)`` â€” always.

        Returns:
            ``np.dtype(bool)``.

        Examples:
            ```pycon
            >>> from supervision.detection.compact_mask import CompactMask
            >>> import numpy as np
            >>> cm = CompactMask(
            ...     [], np.empty((0, 2), dtype=np.int32),
            ...     np.empty((0, 2), dtype=np.int32), (100, 100))
            >>> cm.dtype
            dtype('bool')

            ```
        )r   r'   rQ   rö   s    r   r'   zCompactMask.dtypeC  s   € õ& Œx�‰~Œ~Ðr   únpt.NDArray[np.int64]c                ó`   — t          j        d„ | j        D ¦   «         t           j        ¬¦  «        S )a
  Compute the area (``True`` pixel count) of each mask.

        Note:
            The implementation iterates over the N individual RLE arrays in a
            Python loop (one :func:`_rle_area` call per mask). This is negligible
            for typical N, but callers processing thousands of detections per
            frame should be aware of the per-mask Python-level overhead.

        Returns:
            int64 array of shape ``(N,)`` with per-mask pixel counts.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> from supervision.detection.compact_mask import CompactMask
            >>> masks = np.zeros((2, 100, 100), dtype=bool)
            >>> masks[0, 0:10, 0:10] = True  # 100 pixels
            >>> masks[1, 0:5, 0:5] = True    # 25 pixels
            >>> xyxy = np.array([[0, 0, 9, 9], [0, 0, 4, 4]], dtype=np.float32)
            >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(100, 100))
            >>> cm.area.tolist()
            [100, 25]

            ```
        c                ó,   — g | ]}t          |¦  «        ‘ŒS r"   )r   ©r#   r   s     r   r%   z$CompactMask.area.<locals>.<listcomp>s  s   € Ð>Ð>Ð>¨C� 3™œÐ>Ð>Ð>r   r&   )r   rc   r¬   r/   rö   s    r   ÚareazCompactMask.areaX  s,   € õ6 ŒxÐ>Ð>°4´:Ð>Ñ>Ô>ÅbÄhÐOÑOÔOÐOr   NÚaxisúint | tuple[int, ...] | Noneú npt.NDArray[np.int64] | np.int64c                óÖ   — |dk    r| j         S t          t          j        t          j                 t          j        z  |                      ¦   «                              |¬¦  «        ¦  «        S )a"  NumPy-compatible sum with a fast path for per-mask area.

        When ``axis=(1, 2)``, returns the per-mask True-pixel count via
        :attr:`area` without materialising the full dense array.

        Args:
            axis: Axis or axes to sum over.

        Returns:
            Sum result matching NumPy semantics.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> from supervision.detection.compact_mask import CompactMask
            >>> masks = np.zeros((1, 10, 10), dtype=bool)
            >>> masks[0, 0:3, 0:3] = True
            >>> xyxy = np.array([[0, 0, 2, 2]], dtype=np.float32)
            >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(10, 10))
            >>> cm.sum(axis=(1, 2)).tolist()
            [9]

            ```
        )r   r   ©r  )r  r   ÚnptÚNDArrayr   r/   rò   r   )r¶   r  s     r   r   zCompactMask.sumu  sN   € ð6 �6Š>ˆ>Ø”9ÐÝ•C”K¥¤Ô)­B¬HÑ4°d·m²m±o´o×6IÒ6IÈtÐ6IÑ6TÔ6TÑUÔUÐUr   úint | np.integerc                ó   — d S rµ   r"   ©r¶   ró   s     r   Ú__getitem__zCompactMask.__getitem__”  s   € ØMPÈSr   úMslice | list[int] | list[bool] | npt.NDArray[np.int_] | npt.NDArray[np.bool_]c                ó   — d S rµ   r"   r  s     r   r  zCompactMask.__getitem__—  s	   € ð �cr   ú`int | np.integer | slice | list[int] | list[bool] | npt.NDArray[np.int_] | npt.NDArray[np.bool_]ú#npt.NDArray[np.bool_] | CompactMaskc                óL  ‡ — t          |t          t          j        f¦  «        rÕt          |¦  «        }‰ j        \  }}t          j        ||ft          ¬¦  «        }t          ‰ j        |df         ¦  «        }t          ‰ j        |df         ¦  «        }t          ‰ j        |df         ¦  «        }t          ‰ j        |df         ¦  «        }	t          ‰ j
        |         ||¦  «        }
|
||	|	|z   …|||z   …f<   |S t          |t          ¦  «        rhd„ ‰ j
        |         D ¦   «         }t          |‰ j        |                              ¦   «         ‰ j        |                              ¦   «         ‰ j        ¦  «        S t          |t          j        ¦  «        r+|j        t          k    rt          j        |¦  «        d         }n‰t          |t"          ¦  «        rGt%          d„ |D ¦   «         ¦  «        r.t          j        t          j        |t          ¬¦  «        ¦  «        }n-t          j        t#          |¦  «        t          j        ¬¦  «        }ˆ fd„|D ¦   «         }‰ j        |                              ¦   «         }‰ j        |                              ¦   «         }t          |||‰ j        ¦  «        S )u8  Index into the mask collection.

        * ``int`` â†’ dense ``(H, W)`` bool array (for annotators, iterators).
        * ``slice | list | ndarray`` â†’ new :class:`CompactMask` (for filtering).

        Args:
            index: An integer returns a dense ``(H, W)`` mask.  Any other
                supported index type returns a new :class:`CompactMask`.

        Returns:
            Dense ``(H, W)`` ``np.ndarray`` for integer index, or a new
            :class:`CompactMask` for all other index types.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> from supervision.detection.compact_mask import CompactMask
            >>> masks = np.zeros((3, 20, 20), dtype=bool)
            >>> xyxy = np.array(
            ...     [[0,0,5,5],[5,5,10,10],[10,10,15,15]], dtype=np.float32)
            >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(20, 20))
            >>> cm[0].shape        # int â†’ dense (H, W)
            (20, 20)
            >>> len(cm[[0, 2]])    # list â†’ CompactMask
            2

            ```
        r&   r   r   c                ó6   — g | ]}|                      ¦   «         ‘ŒS r"   r  r
  s     r   r%   z+CompactMask.__getitem__.<locals>.<listcomp>Ö  s    € ÐEÐEÐE¨C˜SŸXšX™ZœZÐEÐEÐEr   c              3  óX   K  — | ]%}t          |t          t          j        f¦  «        V — Œ&d S rµ   )rx   rQ   r   rK   )r#   Úitems     r   ú	<genexpr>z*CompactMask.__getitem__.<locals>.<genexpr>á  sD   è è € ð -
ð -
Ø37�J�t�d¥B¤HÐ-Ñ.Ô.ð-
ð -
ð -
ð -
ð -
ð -
r   c                óh   •— g | ].}‰j         t          |¦  «                                      ¦   «         ‘Œ/S r"   )r¬   r   r  )r#   rÆ   r¶   s     €r   r%   z+CompactMask.__getitem__.<locals>.<listcomp>è  s2   ø€ ÐMÐMÐM¸�D”J�s 8™}œ}Ô-×2Ò2Ñ4Ô4ÐMÐMÐMr   )rx   r   r   Úintegerrª   r¿   rQ   r©   r«   r   r¬   Úslicer¨   r  Úndarrayr'   rÝ   ÚlistÚallrO   r|   Úintp)r¶   ró   ÚidxrÁ   rÂ   rs   r   r   rÇ   ri   r¤   Úselected_rlesÚidx_arrÚnew_rlesÚnew_crop_shapesÚnew_offsetss   `               r   r  zCompactMask.__getitem__¡  su  ø€ õP �e�c¥2¤:Ð.Ñ/Ô/ð 
	Ý�e‘*”*ˆCØÔ,‰LˆE�5Ý,.¬H°e¸U°^Í4Ð,PÑ,PÔ,PˆFÝ˜Ô*¨3°¨6Ô2Ñ3Ô3ˆFÝ˜Ô*¨3°¨6Ô2Ñ3Ô3ˆFÝ�T”] 3¨ 6Ô*Ñ+Ô+ˆBÝ�T”] 3¨ 6Ô*Ñ+Ô+ˆBÝ& t¤z°#¤¸ÀÑGÔGˆDØ9=ˆF�2˜˜V™Ð# R¨"¨v©+Ð%5Ð5Ñ6ØˆMå�e�UÑ#Ô#ð 	ØEÐE°4´:¸eÔ3DÐEÑEÔEˆMÝØØÔ! %Ô(×-Ò-Ñ/Ô/Ø”˜eÔ$×)Ò)Ñ+Ô+ØÔ!ñ	ô ð õ �e�RœZÑ(Ô(ð 	=¨U¬[½DÒ-@Ð-@Ý”h˜u‘o”o aÔ(ˆGˆGÝ˜�tÑ$Ô$ð 	=­ð -
ð -
Ø;@ð-
ñ -
ô -
ñ *
ô *
ð 	=õ ”n¥R¤Z°½TÐ%BÑ%BÔ%BÑCÔCˆGˆGå”j¥ e¡¤µB´GÐ<Ñ<Ô<ˆGàMÐMÐMÐMÀWÐMÑMÔMˆØ15Ô1BÀ7Ô1K×1PÒ1PÑ1RÔ1RˆØ-1¬]¸7Ô-C×-HÒ-HÑ-JÔ-JˆÝ˜8 _°kÀ4ÔCTÑUÔUÐUr   r'   únp.dtype[np.generic] | Noneúnpt.NDArray[np.generic]c                ó\   — |                       ¦   «         }|�|                     |¦  «        S |S )aÑ  NumPy interop: materialise as a dense ``(N, H, W)`` array.

        Called by ``np.asarray(compact_mask)`` and similar NumPy functions.

        Args:
            dtype: Optional dtype to cast the result to.

        Returns:
            Dense boolean array of shape ``(N, H, W)``.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> from supervision.detection.compact_mask import CompactMask
            >>> masks = np.zeros((1, 10, 10), dtype=bool)
            >>> xyxy = np.array([[0, 0, 5, 5]], dtype=np.float32)
            >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(10, 10))
            >>> np.asarray(cm).shape
            (1, 10, 10)

            ```
        )rò   r€   )r¶   r'   rs   s      r   Ú	__array__zCompactMask.__array__í  s.   € ð2 —’‘”ˆØÐØ—=’= Ñ'Ô'Ð'Øˆr   ÚotherÚobjectrQ   c                ób  — t          |t          ¦  «        rFt          t          j        |                      ¦   «         |                     ¦   «         ¦  «        ¦  «        S t          |t          j        ¦  «        r4t          t          j        |                      ¦   «         |¦  «        ¦  «        S t          S )aÖ  Element-wise equality with another :class:`CompactMask` or ndarray.

        Args:
            other: Another :class:`CompactMask` or ``np.ndarray``.

        Returns:
            ``True`` if all masks are pixel-identical.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> from supervision.detection.compact_mask import CompactMask
            >>> masks = np.zeros((1, 10, 10), dtype=bool)
            >>> xyxy = np.array([[0, 0, 5, 5]], dtype=np.float32)
            >>> cm1 = CompactMask.from_dense(masks, xyxy, image_shape=(10, 10))
            >>> cm2 = CompactMask.from_dense(masks, xyxy, image_shape=(10, 10))
            >>> cm1 == cm2
            True

            ```
        )rx   r¨   rQ   r   Úarray_equalrò   r#  ÚNotImplemented)r¶   r1  s     r   Ú__eq__zCompactMask.__eq__  s€   € õ, �e�[Ñ)Ô)ð 	KÝ�œ t§}¢}¡¤¸¿ºÑ8HÔ8HÑIÔIÑJÔJÐJÝ�e�RœZÑ(Ô(ð 	@Ý�œ t§}¢}¡¤¸Ñ>Ô>Ñ?Ô?Ð?ÝÐr   Ú
masks_listúlist[CompactMask]c                óˆ  — | st          d¦  «        ‚| d         j        }| dd…         D ]'}|j        |k    rt          d|› d|j        › �¦  «        ‚Œ(g }| D ]}|                     |j        ¦  «         Œt	          j        d„ | D ¦   «         d¬¦  «        }t	          j        d	„ | D ¦   «         d¬¦  «        }t          ||||¦  «        S )
af  Concatenate multiple :class:`CompactMask` objects into one.

        All inputs must have the same ``image_shape``.

        Args:
            masks_list: Non-empty list of :class:`CompactMask` objects.

        Returns:
            A new :class:`CompactMask` containing every mask from the inputs,
            in order.

        Raises:
            ValueError: If ``masks_list`` is empty or image shapes differ.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> from supervision.detection.compact_mask import CompactMask
            >>> masks1 = np.zeros((2, 50, 50), dtype=bool)
            >>> masks2 = np.zeros((3, 50, 50), dtype=bool)
            >>> xyxy1 = np.array([[0,0,10,10],[10,10,20,20]], dtype=np.float32)
            >>> xyxy2 = np.array(
            ...     [[0,0,5,5],[5,5,10,10],[10,10,15,15]], dtype=np.float32)
            >>> cm1 = CompactMask.from_dense(masks1, xyxy1, image_shape=(50, 50))
            >>> cm2 = CompactMask.from_dense(masks2, xyxy2, image_shape=(50, 50))
            >>> len(CompactMask.merge([cm1, cm2]))
            5

            ```
        z2Cannot merge an empty list of CompactMask objects.r   r   Nz>Cannot merge CompactMask objects with different image shapes: z vs c                ó   — g | ]	}|j         ‘Œ
S r"   )r©   ©r#   Úcms     r   r%   z%CompactMask.merge.<locals>.<listcomp>`  s   € Ð2Ð2Ð2 ˆRŒ_Ð2Ð2Ð2r   r  c                ó   — g | ]	}|j         ‘Œ
S r"   rÿ   r;  s     r   r%   z%CompactMask.merge.<locals>.<listcomp>c  s   € Ð.Ð.Ð.˜RˆRŒ[Ð.Ð.Ð.r   )r   rª   rb   r¬   r   rß   r¨   )r7  r±   r<  r*  r+  r,  s         r   ÚmergezCompactMask.merge+  s  € ð@ ð 	SÝÐQÑRÔRÐRà  ”mÔ0ˆØ˜Q˜R˜R”.ð 	ð 	ˆBØŒ +Ò-Ð-Ý ð:Ø"ð:ð :Ø(*¬ð:ð :ñô ð ð .ð 13ˆØð 	&ð 	&ˆBØ�OŠO˜BœHÑ%Ô%Ð%Ð%õ 24´Ø2Ð2 zÐ2Ñ2Ô2¸ð2
ñ 2
ô 2
ˆõ .0¬^Ø.Ð. :Ð.Ñ.Ô.°Qð.
ñ .
ô .
ˆõ ˜8 _°kÀ;ÑOÔOÐOr   c           	     óœ  — t          | j        ¦  «        }|dk    rSt          g t          j        dt          j        ¬¦  «        t          j        dt          j        ¬¦  «        | j        ¦  «        S g }g }g }t          |¦  «        D �]ö}|                      |¦  «        }t          | j
        |df         ¦  «        }t          | j
        |df         ¦  «        }t          j        |d¬¦  «        }	t          j        |d¬¦  «        }
|	                     ¦   «         sh|                     t          t          j        dt          ¬¦  «        ¦  «        ¦  «         |                     d¦  «         |                     ||f¦  «         Œøt          j        |	¦  «        d         }t          j        |
¦  «        d         }t          |d         ¦  «        t          |d         ¦  «        }}t          |d         ¦  «        t          |d         ¦  «        }}|||dz   …||dz   …f         }|                     t          |¦  «        ¦  «         |                     ||z
  dz   ||z
  dz   f¦  «         |                     ||z   ||z   f¦  «         �Œøt          |t          j        |t          j        ¬¦  «        t          j        |t          j        ¬¦  «        | j        ¦  «        S )u­  Re-encode all masks using tight bounding boxes.

        When the original ``xyxy`` boxes are padded or loose â€” common with
        object-detector outputs and full-image boxes used in tests â€” each RLE
        crop encodes more background (``False``) pixels than necessary.  This
        method decodes every crop, trims it to the minimal rectangle that
        contains all ``True`` pixels, and re-encodes.  All-``False`` masks are
        normalised to a ``1x1`` all-``False`` crop.

        The call is O(sum of crop areas) â€” suitable as a one-time cleanup
        after accumulating many merges (e.g. after
        :class:`~supervision.detection.tools.inference_slicer.InferenceSlicer`
        tiles are merged).

        Returns:
            A new :class:`CompactMask` with minimal-area crops and updated
            offsets.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> from supervision.detection.compact_mask import CompactMask
            >>> masks = np.zeros((1, 10, 10), dtype=bool)
            >>> masks[0, 3:7, 3:7] = True
            >>> # Deliberately loose bbox: covers the full image.
            >>> xyxy = np.array([[0, 0, 9, 9]], dtype=np.float32)
            >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(10, 10))
            >>> repacked = cm.repack()
            >>> repacked.offsets.tolist()  # tight origin: x1=3, y1=3
            [[3, 3]]

            ```
        r   r½   r&   r   r  r¾   r*   )r-   r¬   r¨   r   rJ   rd   rª   r,   r¤   r   r«   r„   r2   r   r¿   rQ   rÝ   rc   )r¶   rÃ   r*  Únew_crop_shapes_listÚnew_offsets_listrÆ   r¤   Úx1_offÚy1_offÚrows_anyÚcols_anyÚ	y_indicesÚ	x_indicesÚy_minÚy_maxÚx_minÚx_maxÚtights                     r   ÚrepackzCompactMask.repackh  s—  € õD ˜œ
‘O”Oˆ	Ø˜Š>ˆ>ÝØÝ”˜¥r¤xÐ0Ñ0Ô0Ý”˜¥r¤xÐ0Ñ0Ô0ØÔ!ñ	ô ð ð 13ˆØ68ÐØ24Ðå˜iÑ(Ô(ð 	Fñ 	FˆHØ—9’9˜XÑ&Ô&ˆDÝ˜œ x° {Ô3Ñ4Ô4ˆFÝ˜œ x° {Ô3Ñ4Ô4ˆFå”v˜d¨Ð+Ñ+Ô+ˆHÝ”v˜d¨Ð+Ñ+Ô+ˆHà—<’<‘>”>ð à—’Õ 3µB´H¸VÍ4Ð4PÑ4PÔ4PÑ QÔ QÑRÔRÐRØ$×+Ò+¨FÑ3Ô3Ð3Ø ×'Ò'¨°Ð(8Ñ9Ô9Ð9Øåœ Ñ*Ô*¨1Ô-ˆIÝœ Ñ*Ô*¨1Ô-ˆIÝ˜y¨œ|Ñ,Ô,­c°)¸B´-Ñ.@Ô.@�5ˆEÝ˜y¨œ|Ñ,Ô,­c°)¸B´-Ñ.@Ô.@�5ˆEà˜ ¨¡Ð*¨E°E¸A±IÐ,=Ð=Ô>ˆEØ�OŠOÕ/°Ñ6Ô6Ñ7Ô7Ð7Ø ×'Ò'¨°©¸Ñ):¸EÀE¹MÈAÑ<MÐ(NÑOÔOÐOØ×#Ò# V¨e¡^°V¸e±^Ð$DÑEÔEÐEÑEåØÝŒHÐ)µ´Ð:Ñ:Ô:ÝŒHÐ%­R¬XÐ6Ñ6Ô6ØÔñ	
ô 
ð 	
r   ÚdxÚdyÚnew_image_shapec           	     óf  — |\  }}|dk    s|dk    rt          d¦  «        ‚t          | ¦  «        }|dk    rNt          g t          j        dt          j        ¬¦  «        t          j        dt          j        ¬¦  «        |¦  «        S | j        t          j        ||gt          j        ¬¦  «        z   }|dd…df         }|dd…df         }	|| j        dd…df         z   dz
  }
|	| j        dd…df         z   dz
  }|dk     |	dk     z  |
|k    z  ||k    z  }| 	                    ¦   «         s;t          t          | j        ¦  «        | j                             ¦   «         ||¦  «        S g }g }g }t          |¦  «        D �]p}t          ||         ¦  «        }t          |	|         ¦  «        }t          |
|         ¦  «        }t          ||         ¦  «        }||         sƒ|                     | j        |         ¦  «         |                     t          | j        |df         ¦  «        t          | j        |df         ¦  «        f¦  «         |                     ||f¦  «         Œât!          d|¦  «        }t!          d|¦  «        }t#          |dz
  |¦  «        }t#          |dz
  |¦  «        }||k    s||k    r«t#          t!          |d¦  «        |dz
  ¦  «        }t#          t!          |d¦  «        |dz
  ¦  «        }|                     t%          t          j        dt(          ¬¦  «        ¦  «        ¦  «         |                     d¦  «         |                     ||f¦  «         �Œß|                      |¦  «        }|||z
  ||z
  dz   …||z
  ||z
  dz   …f         }|                     t%          |¦  «        ¦  «         |                     ||z
  dz   ||z
  dz   f¦  «         |                     ||f¦  «         �Œrt          |t          j        |t          j        ¬¦  «        t          j        |t          j        ¬¦  «        |¦  «        S )aâ  Return a new :class:`CompactMask` with adjusted offsets and image shape.

        Used by :class:`~supervision.detection.tools.inference_slicer.InferenceSlicer`
        to relocate tile-local masks into full-image coordinates without
        materialising the dense ``(N, H, W)`` array.

        Args:
            dx: Pixels to add to every mask's ``x1`` offset.
            dy: Pixels to add to every mask's ``y1`` offset.
            new_image_shape: ``(H, W)`` of the full (destination) image.

        Returns:
            New :class:`CompactMask` with updated offsets and image shape.
            Crops are clipped to stay inside ``new_image_shape``; masks fully
            outside are represented as ``1x1`` all-False crops.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> from supervision.detection.compact_mask import CompactMask
            >>> masks = np.zeros((1, 20, 20), dtype=bool)
            >>> xyxy = np.array([[5, 5, 15, 15]], dtype=np.float32)
            >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(20, 20))
            >>> cm2 = cm.with_offset(100, 200, new_image_shape=(400, 400))
            >>> cm2.offsets[0].tolist()
            [105, 205]

            ```
        r   ú0new_image_shape must contain positive dimensionsr½   r&   Nr   r¾   )r   r-   r¨   r   rJ   rd   r«   rc   r©   r„   r$  r¬   r  r,   r   r2   rl   r1   r   r¿   rQ   r¤   )r¶   rN  rO  rP  r›   rœ   rÃ   r,  Úx1sÚy1sÚx2sÚy2sÚ
needs_clipÚout_rlesÚout_crop_shapesÚout_offsets_listrÆ   rÇ   ri   rÈ   rj   Úix1Úiy1Úix2Úiy2Úanchor_xÚanchor_yr¤   Úclippeds                                r   Úwith_offsetzCompactMask.with_offset»  sD  € ðF '‰ˆˆuØ�AŠ:ˆ:˜ !š˜ÝÐOÑPÔPÐPå˜‘I”Iˆ	Ø˜Š>ˆ>ÝØÝ”˜¥r¤xÐ0Ñ0Ô0Ý”˜¥r¤xÐ0Ñ0Ô0Øñ	ô ð ð .2¬]½R¼XØ�ˆH�BœHð>
ñ >
ô >
ñ .
ˆð ˜!˜!˜!˜Q˜$ÔˆØ˜!˜!˜!˜Q˜$ÔˆØ�DÔ% a a a¨ dÔ+Ñ+¨aÑ/ˆØ�DÔ% a a a¨ dÔ+Ñ+¨aÑ/ˆð �1ŠW˜˜qšÑ! S¨E¢\Ñ2°c¸U²lÑCð 	ð �~Š~ÑÔð 	åÝ�T”ZÑ Ô ØÔ!×&Ò&Ñ(Ô(ØØñ	ô ð ð 13ˆØ13ˆØ24Ðå˜iÑ(Ô(ð "	0ñ "	0ˆHÝ�S˜”]Ñ#Ô#ˆBÝ�S˜”]Ñ#Ô#ˆBÝ�S˜”]Ñ#Ô#ˆBÝ�S˜”]Ñ#Ô#ˆBà˜hÔ'ð 	Ø—’ ¤
¨8Ô 4Ñ5Ô5Ð5Ø×&Ò&å˜DÔ-¨h¸¨kÔ:Ñ;Ô;Ý˜DÔ-¨h¸¨kÔ:Ñ;Ô;ðñô ð ð !×'Ò'¨¨R¨Ñ1Ô1Ð1Øå�a˜‘*”*ˆCÝ�a˜‘*”*ˆCÝ�e˜a‘i Ñ$Ô$ˆCÝ�e˜a‘i Ñ$Ô$ˆCà�SŠyˆy˜C #šI˜IÝ�s 2 q™zœz¨5°1©9Ñ5Ô5�Ý�s 2 q™zœz¨5°1©9Ñ5Ô5�Ø—’Õ 3µB´H¸VÍ4Ð4PÑ4PÔ4PÑ QÔ QÑRÔRÐRØ×&Ò& vÑ.Ô.Ð.Ø ×'Ò'¨°8Ð(<Ñ=Ô=Ð=Ùà—9’9˜XÑ&Ô&ˆDØ˜3 ™8 c¨B¡h°¡lÐ2°C¸"±H¸sÀR¹xÈ!¹|Ð4KÐKÔLˆGØ�OŠOÕ/°Ñ8Ô8Ñ9Ô9Ð9Ø×"Ò" C¨#¡I°¡M°3¸±9¸q±=Ð#AÑBÔBÐBØ×#Ò# S¨# JÑ/Ô/Ð/Ñ/åØÝŒH�_­B¬HÐ5Ñ5Ô5ÝŒHÐ%­R¬XÐ6Ñ6Ô6Øñ	
ô 
ð 	
r   c                óø  ‡ ‡‡‡‡— ddl m} |\  }}|dk    s|dk    rt          d¦  «        ‚||f‰ j        k    rRt	          t          ‰ j        ¦  «        ‰ j                             ¦   «         ‰ j	                             ¦   «         |¦  «        S t          ‰ ¦  «        dk    rNt	          g t          j        dt          j        ¬¦  «        t          j        dt          j        ¬¦  «        |¦  «        S ‰ j        \  }}||z  }||z  }‰ j	        dd…df                              t          j        ¦  «        }	‰ j	        dd…df                              t          j        ¦  «        }
|	‰ j        dd…df         z   dz
  }|
‰ j        dd…df         z   dz
  }t          j        t          j        |	|z  ¦  «        d|dz
  ¦  «                             t          j        ¦  «        }t          j        t          j        |
|z  ¦  «        d|dz
  ¦  «                             t          j        ¦  «        }t          j        t          j        ||z  ¦  «        d|dz
  ¦  «                             t          j        ¦  «        }t          j        t          j        ||z  ¦  «        d|dz
  ¦  «                             t          j        ¦  «        }t          j        d||z
  dz   ¦  «                             t          j        ¦  «        Št          j        d||z
  dz   ¦  «                             t          j        ¦  «        Š‰ j        dd…df         Š‰ j        dd…df         Šˆˆˆˆˆ fd„t'          t          ‰ ¦  «        ¦  «        D ¦   «         }t          ‰ ¦  «        }|t(          k    rj |t+          |t-          j        ¦   «         pd	¦  «        ¬
¦  «        5 }t          |                     d„ |¦  «        ¦  «        }ddd¦  «         n# 1 swxY w Y   nd„ |D ¦   «         }t          j        ‰‰f¦  «                             t          j        ¦  «        }t          j        ||f¦  «                             t          j        ¦  «        }t	          ||||¦  «        S )u4  Return a new CompactMask scaled to a different image resolution.

        Each crop mask is resized with nearest-neighbour interpolation.
        Sparse masks use direct RLE arithmetic (:func:`_rle_resize`); dense
        masks fall back to ``cv2.resize(INTER_NEAREST)``.  Offsets and crop
        dimensions are scaled proportionally to the new image size.

        Performance notes:

        * Coordinate arithmetic is fully vectorised (no Python loop over N).
        * All-``False`` crops skip decode/resize entirely.
        * For N >= 8, resize runs in a thread pool â€” NumPy and OpenCV
          release the GIL so crops execute in parallel on multi-core CPUs.

        Args:
            new_image_shape: ``(H, W)`` of the target image.

        Returns:
            New :class:`CompactMask` with updated ``image_shape``, scaled
            offsets, scaled crop shapes, and re-encoded RLE crops.

        Raises:
            ValueError: If any dimension in *new_image_shape* is ``<= 0``.

        Examples:
            ```pycon
            >>> import numpy as np
            >>> from supervision.detection.compact_mask import CompactMask
            >>> masks = np.zeros((1, 100, 100), dtype=bool)
            >>> masks[0, 20:40, 30:60] = True
            >>> xyxy = np.array([[30, 20, 59, 39]], dtype=np.float32)
            >>> cm = CompactMask.from_dense(masks, xyxy, image_shape=(100, 100))
            >>> small = cm.resize((50, 50))
            >>> small.shape
            (1, 50, 50)
            >>> small.offsets[0].tolist()
            [15, 10]

            ```
        r   )ÚThreadPoolExecutorrR  r½   r&   Nr   c           
     óÌ   •— g | ]`}‰j         |         t          ‰|         ¦  «        t          ‰|         ¦  «        t          ‰|         ¦  «        t          ‰|         ¦  «        f‘ŒaS r"   )r¬   r   )r#   ÚiÚnew_crop_hsÚnew_crop_wsÚorig_crop_hsÚorig_crop_wsr¶   s     €€€€€r   r%   z&CompactMask.resize.<locals>.<listcomp>”  sr   ø€ ð 	
ð 	
ð 	
ð ð ”
˜1”Ý�L ”OÑ$Ô$Ý�L ”OÑ$Ô$Ý�K ”NÑ#Ô#Ý�K ”NÑ#Ô#ðð	
ð 	
ð 	
r   rÕ   )Úmax_workersc                ó   — t          | Ž S rµ   ©r¦   )Úas    r   ú<lambda>z$CompactMask.resize.<locals>.<lambda>£  s   € ¥|°QÐ'7€ r   c                ó    — g | ]}t          |Ž ‘ŒS r"   rm  )r#   rn  s     r   r%   z&CompactMask.resize.<locals>.<listcomp>¦  s   € Ð7Ð7Ð7¨Q� aÐ(Ð7Ð7Ð7r   )Úconcurrent.futuresrd  r   rª   r¨   r$  r¬   r©   r  r«   r-   r   rJ   rd   r€   Úfloat64ÚclipÚroundÚmaximumr,   r–   r1   ÚosÚ	cpu_countÚmapr  )r¶   rP  rd  r›   rœ   rÁ   rÂ   ÚsxÚsyrS  rT  rU  rV  Únew_x1sÚnew_y1sÚnew_x2sÚnew_y2sÚargsÚnÚpoolr*  r+  r,  rg  rh  ri  rj  s   `                      @@@@r   r¡   zCompactMask.resize8  st  øøøøø€ ðR 	:Ð9Ð9Ð9Ð9Ð9à&‰ˆˆuØ�AŠ:ˆ:˜ !š˜ÝÐOÑPÔPÐPð
 �5ˆ>˜TÔ.Ò.Ð.ÝÝ�T”ZÑ Ô ØÔ!×&Ò&Ñ(Ô(Ø”×"Ò"Ñ$Ô$Øñ	ô ð õ ˆt‰9Œ9˜Š>ˆ>ÝØÝ”˜¥r¤xÐ0Ñ0Ô0Ý”˜¥r¤xÐ0Ñ0Ô0Øñ	ô ð ð Ô(‰ˆˆuØ�U‰]ˆØ�U‰]ˆð Œm˜A˜A˜A˜q˜DÔ!×(Ò(­¬Ñ4Ô4ˆØŒm˜A˜A˜A˜q˜DÔ!×(Ò(­¬Ñ4Ô4ˆØ�DÔ% a a a¨ dÔ+Ñ+¨aÑ/ˆØ�DÔ% a a a¨ dÔ+Ñ+¨aÑ/ˆå”'�"œ( 3¨¡8Ñ,Ô,¨a°¸±Ñ;Ô;×BÒBÅ2Ä8ÑLÔLˆÝ”'�"œ( 3¨¡8Ñ,Ô,¨a°¸±Ñ;Ô;×BÒBÅ2Ä8ÑLÔLˆÝ”'�"œ( 3¨¡8Ñ,Ô,¨a°¸±Ñ;Ô;×BÒBÅ2Ä8ÑLÔLˆÝ”'�"œ( 3¨¡8Ñ,Ô,¨a°¸±Ñ;Ô;×BÒBÅ2Ä8ÑLÔLˆÝ-/¬ZØˆw˜Ñ  1Ñ$ñ.
ô .
ç
Š&•”Ñ
Ô
ð 	õ .0¬ZØˆw˜Ñ  1Ñ$ñ.
ô .
ç
Š&•”Ñ
Ô
ð 	ð
 Ô(¨¨¨¨A¨Ô.ˆØÔ(¨¨¨¨A¨Ô.ˆð	
ð 	
ð 	
ð 	
ð 	
ð 	
ð 	
ð 	
õ �3˜t™9œ9Ñ%Ô%ð	
ñ 	
ô 	
ˆõ �‰IŒIˆØÕ#Ò#Ð#Ø#Ð#µ°Aµr´|±~´~Ð7JÈÑ0KÔ0KÐLÑLÔLð ÐPTÝ8<Ø—H’HÐ7Ð7¸Ñ>Ô>ñ9ô 9�ðð ð ñ ô ð ð ð ð ð ð øøøð ð ð ð øð
 8Ð7°$Ð7Ñ7Ô7ˆHåœ/¨;¸Ð*DÑEÔE×LÒLÍRÌXÑVÔVˆÝ”o w°Ð&8Ñ9Ô9×@Ò@ÅÄÑJÔJˆÝ˜8 _°kÀ?ÑSÔSÐSs   Î;%O,Ï,O0Ï3O0)
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   r  rµ   )r  r  r   r  )ró   r  r   r¹   )ró   r  r   r¨   )ró   r  r   r  )r'   r-  r   r.  )r1  r2  r   rQ   )r7  r8  r   r¨   )r   r¨   )rN  r   rO  r   rP  r²   r   r¨   )rP  r²   r   r¨   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú	__slots__r·   ÚclassmethodrÑ   rð   rò   r¤   r÷   rú   ÚpropertyrØ   r±   r°   r  r'   r  r   r	   r  r0  r6  Ústaticmethodr>  rM  rb  r¡   r"   r   r   r¨   r¨   5  sÊ  € € € € € ðAð AðF F€Ið
9ð 
9ð 
9ð 
9ð  ðQ<ð Q<ð Q<ñ „[ðQ<ðf ðaDð aDð aDñ „[ðaDðNð ð ð ð@Fð Fð Fð FðBð ð ð ð(!ð !ð !ð !ð
 ð)ð )ð )ñ „Xð)ð* ð!ð !ð !ñ „Xð!ð( ðð ð ñ „Xðð* ðNð Nð Nñ „XðNð@ ðð ð ñ „Xðð( ðPð Pð Pñ „XðPð: 48ðVð Vð Vð Vð Vð> ØPÐPÐPñ „XØPàðð ð ñ „XððJVð JVð JVð JVðZ 48ðð ð ð ð ð<ð ð ð ð@ ð:Pð :Pð :Pñ „\ð:PðxM
ð M
ð M
ð M
ðfw
ð w
ð w
ð w
ðzrTð rTð rTð rTð rTð rTr   r¨   )r   r   r   r   )r   N)r   r   r   r   r   r   r   r   r   r   r   r   )rE   rF   rG   r   rH   r   r   rF   )r_   r   r`   r   r   r   )rE   rh   ri   r   rj   r   r   rF   )rv   r   r   r   )r   r   r   r   r   r   rS   r   r‹   r   r   r   )r   r   r™   r   rš   r   r›   r   rœ   r   r   r   )#r…  Ú
__future__r   rv  Úcollections.abcr   r   r   Útypingr   r   r	   Únumpyr   Únumpy.typingr  Ú&supervision.detection.utils.convertersr
   r   r   r   r   rD   r^   rg   ru   rŠ   r’   r”   Ú__annotations__r–   r—   r˜   r¦   r¨   r"   r   r   ú<module>r‘     s  ððð ð ð  #Ð "Ð "Ð "Ð "Ð "à 	€	€	€	Ø 7Ð 7Ð 7Ð 7Ð 7Ð 7Ð 7Ð 7Ð 7Ð 7Ø &Ð &Ð &Ð &Ð &Ð &Ð &Ð &Ð &Ð &à Ð Ð Ð Ø Ð Ð Ð Ð Ð ð
ð ð ð ð ð ð ð ð ð ð ð ð"ð "ð "ð "ð4 Øðð ð ð ð ðD>ð >ð >ð >ðB5Qð 5Qð 5Qð 5Qðp5ð 5ð 5ð 5ðp0ð 0ð 0ð 0ðfR2ð R2ð R2ð R2ðp  $Ð Ð #Ð #Ð #Ñ #àÐ Ð Ð Ð Ñ ð "Ð Ð !Ð !Ð !Ñ !ð %.Ð Ð -Ð -Ð -Ñ -ð-(ð -(ð -(ð -(ð`uTð uTð uTð uTð uTñ uTô uTð uTð uTð uTr   