
    /j              
      ~   d dl mZ d dlZd dlmZ d dlmZ d dlmZ d dl	Z	d dl
Zd dlZd dlmZmZmZ d dlmZ d dlmZmZmZmZmZmZmZ d d	lmZmZmZ d d
lm Z   G d d          Z! e!            Z" G d d          Z# e             e            d ed          dfd                        Z$ ed          dddddfdQd!Z%e ej&        d"ej'        #          dd$ddd%d&dd'f	dRd9            Z( e            dSdTd<            Z)dUdVdEZ* e            dWdXdI            Z+ e            dJ edK          fdYdP            Z,dS )Z    )annotationsN)Callable)Path)Any)Image	ImageDraw	ImageFont)__version__)IS_COLAB	IS_KAGGLELOGGER	TryExceptopsplt_settingsthreaded)
check_fontcheck_versionis_ascii)increment_pathc                  :    e Zd ZdZd Zddd
Zedd            ZdS )Colorsa  Ultralytics color palette for visualization and plotting.

    This class provides methods to work with the Ultralytics color palette, including converting hex color codes to RGB
    values and accessing predefined color schemes for object detection and pose estimation.

    ## Ultralytics Color Palette

    | Index | Color                                                             | HEX       | RGB               |
    |-------|-------------------------------------------------------------------|-----------|-------------------|
    | 0     | <i class="fa-solid fa-square fa-2xl" style="color: #042aff;"></i> | `#042aff` | (4, 42, 255)      |
    | 1     | <i class="fa-solid fa-square fa-2xl" style="color: #0bdbeb;"></i> | `#0bdbeb` | (11, 219, 235)    |
    | 2     | <i class="fa-solid fa-square fa-2xl" style="color: #f3f3f3;"></i> | `#f3f3f3` | (243, 243, 243)   |
    | 3     | <i class="fa-solid fa-square fa-2xl" style="color: #00dfb7;"></i> | `#00dfb7` | (0, 223, 183)     |
    | 4     | <i class="fa-solid fa-square fa-2xl" style="color: #111f68;"></i> | `#111f68` | (17, 31, 104)     |
    | 5     | <i class="fa-solid fa-square fa-2xl" style="color: #ff6fdd;"></i> | `#ff6fdd` | (255, 111, 221)   |
    | 6     | <i class="fa-solid fa-square fa-2xl" style="color: #ff444f;"></i> | `#ff444f` | (255, 68, 79)     |
    | 7     | <i class="fa-solid fa-square fa-2xl" style="color: #cced00;"></i> | `#cced00` | (204, 237, 0)     |
    | 8     | <i class="fa-solid fa-square fa-2xl" style="color: #00f344;"></i> | `#00f344` | (0, 243, 68)      |
    | 9     | <i class="fa-solid fa-square fa-2xl" style="color: #bd00ff;"></i> | `#bd00ff` | (189, 0, 255)     |
    | 10    | <i class="fa-solid fa-square fa-2xl" style="color: #00b4ff;"></i> | `#00b4ff` | (0, 180, 255)     |
    | 11    | <i class="fa-solid fa-square fa-2xl" style="color: #dd00ba;"></i> | `#dd00ba` | (221, 0, 186)     |
    | 12    | <i class="fa-solid fa-square fa-2xl" style="color: #00ffff;"></i> | `#00ffff` | (0, 255, 255)     |
    | 13    | <i class="fa-solid fa-square fa-2xl" style="color: #26c000;"></i> | `#26c000` | (38, 192, 0)      |
    | 14    | <i class="fa-solid fa-square fa-2xl" style="color: #01ffb3;"></i> | `#01ffb3` | (1, 255, 179)     |
    | 15    | <i class="fa-solid fa-square fa-2xl" style="color: #7d24ff;"></i> | `#7d24ff` | (125, 36, 255)    |
    | 16    | <i class="fa-solid fa-square fa-2xl" style="color: #7b0068;"></i> | `#7b0068` | (123, 0, 104)     |
    | 17    | <i class="fa-solid fa-square fa-2xl" style="color: #ff1b6c;"></i> | `#ff1b6c` | (255, 27, 108)    |
    | 18    | <i class="fa-solid fa-square fa-2xl" style="color: #fc6d2f;"></i> | `#fc6d2f` | (252, 109, 47)    |
    | 19    | <i class="fa-solid fa-square fa-2xl" style="color: #a2ff0b;"></i> | `#a2ff0b` | (162, 255, 11)    |

    ## Pose Color Palette

    | Index | Color                                                             | HEX       | RGB               |
    |-------|-------------------------------------------------------------------|-----------|-------------------|
    | 0     | <i class="fa-solid fa-square fa-2xl" style="color: #ff8000;"></i> | `#ff8000` | (255, 128, 0)     |
    | 1     | <i class="fa-solid fa-square fa-2xl" style="color: #ff9933;"></i> | `#ff9933` | (255, 153, 51)    |
    | 2     | <i class="fa-solid fa-square fa-2xl" style="color: #ffb266;"></i> | `#ffb266` | (255, 178, 102)   |
    | 3     | <i class="fa-solid fa-square fa-2xl" style="color: #e6e600;"></i> | `#e6e600` | (230, 230, 0)     |
    | 4     | <i class="fa-solid fa-square fa-2xl" style="color: #ff99ff;"></i> | `#ff99ff` | (255, 153, 255)   |
    | 5     | <i class="fa-solid fa-square fa-2xl" style="color: #99ccff;"></i> | `#99ccff` | (153, 204, 255)   |
    | 6     | <i class="fa-solid fa-square fa-2xl" style="color: #ff66ff;"></i> | `#ff66ff` | (255, 102, 255)   |
    | 7     | <i class="fa-solid fa-square fa-2xl" style="color: #ff33ff;"></i> | `#ff33ff` | (255, 51, 255)    |
    | 8     | <i class="fa-solid fa-square fa-2xl" style="color: #66b2ff;"></i> | `#66b2ff` | (102, 178, 255)   |
    | 9     | <i class="fa-solid fa-square fa-2xl" style="color: #3399ff;"></i> | `#3399ff` | (51, 153, 255)    |
    | 10    | <i class="fa-solid fa-square fa-2xl" style="color: #ff9999;"></i> | `#ff9999` | (255, 153, 153)   |
    | 11    | <i class="fa-solid fa-square fa-2xl" style="color: #ff6666;"></i> | `#ff6666` | (255, 102, 102)   |
    | 12    | <i class="fa-solid fa-square fa-2xl" style="color: #ff3333;"></i> | `#ff3333` | (255, 51, 51)     |
    | 13    | <i class="fa-solid fa-square fa-2xl" style="color: #99ff99;"></i> | `#99ff99` | (153, 255, 153)   |
    | 14    | <i class="fa-solid fa-square fa-2xl" style="color: #66ff66;"></i> | `#66ff66` | (102, 255, 102)   |
    | 15    | <i class="fa-solid fa-square fa-2xl" style="color: #33ff33;"></i> | `#33ff33` | (51, 255, 51)     |
    | 16    | <i class="fa-solid fa-square fa-2xl" style="color: #00ff00;"></i> | `#00ff00` | (0, 255, 0)       |
    | 17    | <i class="fa-solid fa-square fa-2xl" style="color: #0000ff;"></i> | `#0000ff` | (0, 0, 255)       |
    | 18    | <i class="fa-solid fa-square fa-2xl" style="color: #ff0000;"></i> | `#ff0000` | (255, 0, 0)       |
    | 19    | <i class="fa-solid fa-square fa-2xl" style="color: #ffffff;"></i> | `#ffffff` | (255, 255, 255)   |

    !!! note "Ultralytics Brand Colors"

        For Ultralytics brand colors see [https://www.ultralytics.com/brand](https://www.ultralytics.com/brand).
        Please use the official Ultralytics colors for all marketing materials.

    Attributes:
        palette (list[tuple]): List of RGB color tuples for general use.
        n (int): The number of colors in the palette.
        pose_palette (np.ndarray): A specific color palette array for pose estimation with dtype np.uint8.

    Examples:
        >>> from ultralytics.utils.plotting import Colors
        >>> colors = Colors()
        >>> colors(5, True)  # Returns BGR format: (221, 111, 255)
        >>> colors(5, False)  # Returns RGB format: (255, 111, 221)
    c                &    d} fd|D              _         t           j                    _        t          j        g dg dg dg dg dg dg d	g d
g dg dg dg dg dg dg dg dg dg dg dg dgt          j                   _        dS )zEInitialize colors as hex = matplotlib.colors.TABLEAU_COLORS.values().)042AFF0BDBEBF3F3F300DFB7111F68FF6FDDFF444FCCED0000F344BD00FF00B4FFDD00BA00FFFF26C00001FFB37D24FF7B0068FF1B6CFC6D2FA2FF0Bc                @    g | ]}                     d |           S )#)hex2rgb).0cselfs     _/home/longshao/multi-rider-rag/.venv/lib/python3.11/site-packages/ultralytics/utils/plotting.py
<listcomp>z#Colors.__init__.<locals>.<listcomp>v   s+    <<<!WWW--<<<    )      r   )r6      3   )r6      f   )   r<   r   )r6   r8   r6   )r8      r6   )r6   r;   r6   )r6   r9   r6   )r;   r:   r6   )r9   r8   r6   )r6   r8   r8   )r6   r;   r;   )r6   r9   r9   )r8   r6   r8   )r;   r6   r;   )r9   r6   r9   )r   r6   r   )r   r   r6   )r6   r   r   r6   r6   r6   dtypeN)palettelennnparrayuint8pose_palette)r2   hexss   ` r3   __init__zColors.__init__^   s    
, =<<<t<<<T\""H), (/
 
 
r5   Fiint | torch.Tensorbgrboolreturntuplec                |    | j         t          |          | j        z           }|r|d         |d         |d         fn|S )a   Return a color from the palette by index.

        Args:
            i (int | torch.Tensor): Color index.
            bgr (bool, optional): Whether to return BGR format instead of RGB.

        Returns:
            (tuple): RGB or BGR color tuple.
              r   )rA   intrC   )r2   rJ   rL   r1   s       r3   __call__zColors.__call__   s?     LQ$&)%(/!adAaD!!a/r5   hstrc                :     t           fddD                       S )z?Convert hex color codes to RGB values (i.e. default PIL order).c              3  Z   K   | ]%}t          d |z   d |z   dz            d          V  &dS )rR   rQ      NrS   )r0   rJ   rU   s     r3   	<genexpr>z!Colors.hex2rgb.<locals>.<genexpr>   sC      FFqS1q51q519,-r22FFFFFFr5   )r   rQ      rO   )rU   s   `r3   r/   zColors.hex2rgb   s(     FFFFIFFFFFFr5   NF)rJ   rK   rL   rM   rN   rO   )rU   rV   rN   rO   )__name__
__module____qualname____doc__rI   rT   staticmethodr/    r5   r3   r   r      sp        F FP2
 2
 2
h0 0 0 0 0 G G G \G G Gr5   r   c                      e Zd ZdZ	 	 	 	 	 d?d@dZdAdBdZdCdDdZdEdFdZ	 	 	 	 	 dGdHd)ZdIdJd-Z	dKdLd3Z
d4 ZdMd5ZdNdOd8ZdPdQd;ZedRd>            ZdS )S	Annotatora  Ultralytics Annotator for train/val mosaics and JPGs and predictions annotations.

    Attributes:
        im (Image.Image | np.ndarray): The image to annotate.
        pil (bool): Whether to use PIL or cv2 for drawing annotations.
        font (ImageFont.truetype | ImageFont.load_default): Font used for text annotations.
        lw (int): Line width for drawing.
        skeleton (list[list[int]]): Skeleton structure for keypoints.
        limb_color (np.ndarray): Color palette for limbs.
        kpt_color (np.ndarray): Color palette for keypoints.
        dark_colors (set): Set of colors considered dark for text contrast.
        light_colors (set): Set of colors considered light for text contrast.

    Examples:
        >>> from ultralytics.utils.plotting import Annotator
        >>> im0 = cv2.imread("test.png")
        >>> annotator = Annotator(im0, line_width=10)
        >>> annotator.box_label([10, 10, 100, 100], "person", (255, 0, 0))
    N	Arial.ttfFabc
line_width
int | None	font_sizefontrV   pilrM   examplec                    t          |           }t          |t          j                  }|p|p| _        |p=t	          t          t          |r|j        n|j                  dz  dz            d           _	        |s|j        d         dk    r t          j        |t          j                  }n|j        d         dk    rEt          j        t          j        |t          j        |dddf                   f                    }n/|j        d         dk    rt          j        |dddf                   } j        r.|r|nt          j        |           _         j        j        dvr j                            d           _        t+          j         j        d	           _        	 t1          |rd
n|          }|p9t	          t          t           j        j                  dz  dz            d          }	t3          j        t7          |          |	           _        n(# t:          $ r t3          j                     _        Y nw xY wt?          t@          d          r fd j        _!        ni|j"        j#        s
J d            |j$        j%        r|n|&                                 _        t	           j	        dz
  d           _'         j	        dz   _(        ddgddgddgddgddgddgddgddgddgddgddgddgddgddgddgddgddgddgddgg _)        tT          j+        g d          _,        tT          j+        g d          _-        h d _.        h d  _/        dS )!zjInitialize the Annotator class with image and line width along with color palette for keypoints and limbs.rQ   g~jth?rR   .N   >   RGBRGBArq   rr   zArial.Unicode.ttfgQ?   z9.2.0c                H    j                             |           dd         S )NrQ   r\   )rl   getbbox)xr2   s    r3   <lambda>z$Annotator.__init__.<locals>.<lambda>   s     di.?.?.B.B1Q3.G r5   zOImage not contiguous. Apply np.ascontiguousarray(im) to Annotator input images.rY                        	   
      r\      )r   r   r   r   r}   r}   r}   r   r   r   r   r   rY   rY   rY   rY   rY   rY   rY   )rY   rY   rY   rY   rY   r   r   r   r   r   r   r   r   r   r   r   r   >	   r      r=   r   r6      D      r      r6   rR         r      o   r6         r   r   r   r   r6   r6   r   >   r      &   /   m      O   r   r6   h   r   {   l      r6      r   r   r6   r      r6   $   }   r6   *   r\   r6      r   r      ry   )0r   
isinstancer   rm   maxroundsumsizeshapelwcv2cvtColorCOLOR_GRAY2BGRrD   ascontiguousarraydstack
zeros_like	fromarrayimmodeconvertr   Drawdrawr   r	   truetyperV   rl   	Exceptionload_defaultr   pil_versiongetsizedata
contiguousflags	writeablecopytfsfskeletoncolorsrG   
limb_color	kpt_colordark_colorslight_colors)
r2   r   ri   rk   rl   rm   rn   	non_asciiinput_is_pilr   s
   `         r3   rI   zAnnotator.__init__   s    !)))	!"ek223)3|eE#.Sbgg28*T*TWX*X[`*`$a$acd e e 	7x{a\"c&899!!!)")Rr#rPQr'{9S9S4T*U*UVV!q)"S"1"W+668 	"(Abbeob.A.ADGw|?22'//%00!tw77DI5!"L"5"5MM QCc$',.?.?!.Ce.K(L(Lb$Q$Q%.s4yy$??		 5 5 5%244			5 ['22 H$G$G$G$G	!7%xx'xxx%H.=bbBGGIIDG$'A+q))DGgkDG HHHHHGGFFFGGFFFFFFF'
, !-.n.n.no,-e-e-ef

 

 


 
 
s   &A6H "IIr7   r7   r7   r>   colorrO   	txt_colorrN   c                2    || j         v rdS || j        v rdS |S )a1  Assign text color based on background color.

        Args:
            color (tuple, optional): The background color of the rectangle for text.
            txt_color (tuple, optional): The fallback color of the text.

        Returns:
            (tuple): Text color for label.

        Examples:
            >>> from ultralytics.utils.plotting import Annotator
            >>> im0 = cv2.imread("test.png")
            >>> annotator = Annotator(im0, line_width=10)
            >>> annotator.get_txt_color(color=(104, 31, 17))  # return (255, 255, 255)
        r   r>   )r   r   )r2   r   r   s      r3   get_txt_colorzAnnotator.get_txt_color  s0      D$$$;d''' =r5    labelc           
     d   |                      ||          }t          |t          j                  r|                                }t          |d         t
                    }|rd |d         D             n)t          |d                   t          |d                   f}| j        rX|r,| j        	                    d |D             | j
        |          n!| j                            || j
        |           |r| j                            |          \  }}|d         |k    }	|d         | j        j        d         |z
  k    r| j        j        d         |z
  |d         f}| j                            |d         |	r|d         |z
  n|d         |d         |z   dz   |	r|d         dz   n|d         |z   dz   f|           | j                            |d         |	r|d         |z
  n|d         f||| j                   dS dS |r<t#          j        | j        t'          j        |t                    gd	|| j
                  nUt#          j        | j        |t          |d
                   t          |d                   f|| j
        t"          j                   |rt#          j        |d| j        | j                  d         \  }}|dz  }|d         |k    }	|d         | j        j        d         |z
  k    r| j        j        d         |z
  |d         f}|d         |z   |	r|d         |z
  n
|d         |z   f}
t#          j        | j        ||
|dt"          j                   t#          j        | j        ||d         |	r|d         d
z
  n|d         |z   dz
  fd| j        || j        t"          j                   dS dS )ag  Draw a bounding box on an image with a given label.

        Args:
            box (tuple): The bounding box coordinates (x1, y1, x2, y2).
            label (str, optional): The text label to be displayed.
            color (tuple, optional): The background color of the rectangle.
            txt_color (tuple, optional): The color of the text.

        Examples:
            >>> from ultralytics.utils.plotting import Annotator
            >>> im0 = cv2.imread("test.png")
            >>> annotator = Annotator(im0, line_width=10)
            >>> annotator.box_label(box=[10, 20, 30, 40], label="person")
        r   c                ,    g | ]}t          |          S rd   rZ   r0   bs     r3   r4   z'Annotator.box_label.<locals>.<listcomp>B  s    %%%c!ff%%%r5   rR   c                ,    g | ]}t          |          S rd   r]   r   s     r3   r4   z'Annotator.box_label.<locals>.<listcomp>E  s    '''aq'''r5   widthoutlinefillr   rl   r?   TrQ   rp   	thicknesslineType	fontScaler   N)r   r   torchTensortolistlistrS   rm   r   polygonr   	rectanglerl   r   r   r   textr   	polylinesrD   asarrayLINE_AAgetTextSizer   r   r   putText)r2   boxr   r   r   multi_pointsp1wrU   outsidep2s              r3   	box_labelzAnnotator.box_label.  s    &&ui88	c5<(( 	**,,C!#a&$//)5U%%c!f%%%%CAKKSQRV;U8 &	 ZDI''3'''tw    #'9#6#6s$'SX#6#Y#Y 
py((//1Q%1*a547<?Q...a1,be3B	##U;BqEAIIbeRUQY]Y`LsBqETUIIfhijfknoforsfst $   
 	1G'Fr!uqyyAGU^eienooooo
p 
p CM"*S4445tUDG  #&=c#a&kk3s1v;;7$'\_\g$ $ $  ua47dgVVVWXY1QQ%1*a547=+a///q)A-r!u4BUQYW C1		"Q%!)Cdgr2ub#+FFFGUCBqEAIIbeai!mDG"g [	 	 	 	 	 	 r5         ?im_gputorch.Tensoralphafloatretina_masksc                H   | j         r0t          j        | j                                                  | _        |t          |t          j                  s
J d            | j                                        }t          |          D ](\  }}||         ||                    t                    <   )t          j        | j        d|z
  ||d          | _        nt          |t          j                  s
J d            t          |          dk    r\|                    ddd                                                                                                          dz  | j        dd<   dS |j        |j        k    r|                    |j                  }| j        j        dd         \  }	}
|st-          j        |d                                         |	|
f          d         dk    }t          j        | j                                      |j                                      ddd                              d                                                                          d	z  }t          j        ||j        t          j        
          d	z  }|ddddf         }|                    d          }|||z  z  }d||z  z
                      d          }|                    d          j         }|                    dg                              ddd                                          }||d         z  |z   }|dz  !                                                                                                | j        dd<   | j         r| "                    | j                   dS dS )a  Plot masks on image.

        Args:
            masks (torch.Tensor | np.ndarray): Predicted masks with shape [n, h, w].
            colors (list[list[int]]): Colors for predicted masks, [[r, g, b] * n].
            im_gpu (torch.Tensor | None): Image on GPU with shape [3, h, w], range [0, 1].
            alpha (float, optional): Mask transparency: 0.0 fully transparent, 1.0 opaque.
            retina_masks (bool, optional): Whether to use high resolution masks or not.
        Nz9`masks` must be a np.ndarray if `im_gpu` is not provided.rR   r   z7'masks' must be a torch.Tensor if 'im_gpu' is provided.rQ   r6   r  g     o@)devicer@   rp   dim)dimsr   )#rm   rD   r   r   r   r   ndarray	enumerateastyperM   r   addWeightedr   r   rB   permuter   cpunumpyr  tor   r   scale_masksr	  
from_numpyfliptensorfloat32	unsqueezecumprodr   valuesbyter   )r2   masksr   r  r  r
  overlayrJ   maskihiwmasks_colorinv_alpha_masksmcss                 r3   r!  zAnnotator.masksk  sA    8 	1j))..00DG>eRZ00mm2mmm0gllnnG$U++ 7 74-3AYD))**odgq5y'5!LLDGGeU\22mm4mmm25zzQ#^^Aq!44??AAEEGGMMOORUU
},,5<00W]2A2&FB d(9(9(;(;b"XFFqICO $TW--00>>FFq!QOOTTUVWWbbddjjllott  \&U]SSSV[[FAAAtTM*FOOA&&E6E>2K 55=099!<<O//a/((/C[[qc[**221a;;FFHHFob11C7F 3,,,..2244::<<DGAAAJ8 	$NN47#####	$ 	$r5     r*  T      ?r   radiuskpt_line
conf_thresr   tuple | Nonec                r   ||n| j         }| j        r0t          j        | j                                                  | _        |j        \  }}|dk    o|dv }	||	z  }t          |          D ]\  }
}|p/|	r| j        |
         	                                nt          |
          }|d         |d         }}||d         z  dk    rv||d         z  dk    rgt          |          dk    r|d         }||k     rt          j        | j        t          |          t          |          f||dt          j        	           |r|j        d         }t          | j                  D ]\  }
}t          ||d         dz
  df                   t          ||d         dz
  df                   f}t          ||d         dz
  df                   t          ||d         dz
  df                   f}|dk    r3||d         dz
  df         }||d         dz
  df         }||k     s||k     r|d         |d         z  dk    s-|d         |d         z  dk    s|d         dk     s|d         dk     r|d         |d         z  dk    s-|d         |d         z  dk    s|d         dk     s|d         dk     rGt          j        | j        |||p| j        |
         	                                t          t          j        | j         dz                      t          j        
           | j        r|                     | j                   dS dS )a  Plot keypoints on the image.

        Args:
            kpts (torch.Tensor): Keypoints, shape [17, 3] (x, y, confidence).
            shape (tuple, optional): Image shape (h, w).
            radius (int, optional): Keypoint radius.
            kpt_line (bool, optional): Draw lines between keypoints.
            conf_thres (float, optional): Confidence threshold.
            kpt_color (tuple, optional): Keypoint color.

        Notes:
            - `kpt_line=True` currently only supports human pose plotting.
            - Modifies self.im in-place.
            - If self.pil is True, converts image to numpy array and back to PIL.
        Nry   >   rQ   rp   r   rR   rp   rQ   r   )r   r   )r   rm   rD   r   r   r   r   r  r   r   r   rB   r   circlerS   r   r   liner   ceilr   )r2   kptsr   r,  r-  r.  r   nkptndimis_poserJ   kcolor_kx_coordy_coordconfskpos1pos2conf1conf2s                        r3   r4  zAnnotator.kpts  sl   0 "-478 	1j))..00DGZ
d"*/GdOO 	m 	mDAqY'$XDN1$5$<$<$>$>$>vVWyyG tQqTWGq!Q&&7U1X+=+B+Bq66Q;;Q4Dj(( 
47S\\3w<<$@&'SU`c`kllll 	:b>D"4=11  2D"Q%!)a0113tRUQYN7K3L3LMD"Q%!)a0113tRUQYN7K3L3LM199 "Q%!)a0E "Q%!)a0Ez))UZ-?-? 7U1X%**d1ga.@A.E.EaSTX\]^X_bcXcXc7U1X%**d1ga.@A.E.EaSTX\]^X_bcXcXcG<!3!:!:!<!<!"'$'A+"6"677 [     8 	$NN47#####	$ 	$r5   rR   r   rS   c                @    | j                             ||||           dS )z"Add rectangle to image (PIL-only).N)r   r   )r2   xyr   r   r   s        r3   r   zAnnotator.rectangle  s$    	Bgu55555r5   toprd   r   anchor	box_colorc           
     \   | j         r| j                            |          \  }}|dk    r|dxx         d|z
  z  cc<   |                    d          D ]}|ra| j                            |          \  }}| j                            |d         |d         |d         |z   dz   |d         |z   dz   f|           | j                            |||| j                   |dxx         |z  cc<   dS |rt          j        |d| j	        | j
                  d         \  }}|dz  }|d         |k    }	|d         |z   |	r|d         |z
  n
|d         |z   f}
t          j        | j        ||
|d	t          j                   t          j        | j        ||d| j	        || j
        t          j        
           dS )a  Add text to an image using PIL or cv2.

        Args:
            xy (list[int]): Top-left coordinates for text placement.
            text (str): Text to be drawn.
            txt_color (tuple, optional): Text color.
            anchor (str, optional): Text anchor position ('top' or 'bottom').
            box_color (tuple, optional): Box background color with optional alpha.
        bottomrR   
r   r   r   r   rp   r   r   N)rm   rl   r   splitr   r   r   r   r   r   r   r   r   r   )r2   rC  r   r   rE  rF  r  rU   r2  r  r  s              r3   r   zAnnotator.text  s    8 	k9$$T**DAq!!1Q

4((   f9,,T22DAqI''A1r!uqy1}beaiRSm(T[d'eee	r4idiHHH1
   KtQ$'TWUUUVWX1QQ%1*UQYW C1		"Q%!)Cdgr2y"ckJJJKr1dgyDG^a^ijjjjjjr5   c                    t          |t          j                  r|nt          j        |          | _        t	          j        | j                  | _        dS )z1Update `self.im` from a NumPy array or PIL image.N)r   r   r   r   r   r   r   )r2   r   s     r3   r   zAnnotator.fromarray  s?    "2u{33L""9L9LN47++			r5   c                z    t          j        | j                  }|rt          j        |ddddf                   n|S )z-Return annotated image as array or PIL image..Nr   )rD   r   r   r   r   )r2   rm   r   s      r3   resultzAnnotator.result  s;    Z  14<ur#ttt)}---"<r5   title
str | Nonec                <   t          j        t          j        | j                  ddddf                   }t
          st          rA	 t          |           dS # t          $ r"}t          j
        d|            Y d}~dS d}~ww xY w|                    |           dS )zShow the annotated image..Nr   z.Unable to display image in Jupyter notebooks: )rN  )r   r   rD   r   r   r   r   displayImportErrorr   warningshow)r2   rN  r   es       r3   rT  zAnnotator.show  s    _RZ00ddd;<< 	!y 	!U U U USPQSSTTTTTTTTTU GG%G     s   A 
B!A>>B	image.jpgfilenamec                ^    t          j        |t          j        | j                             dS )z'Save the annotated image to 'filename'.N)r   imwriterD   r   r   )r2   rW  s     r3   savezAnnotator.save  s&    Hbj1122222r5   bboxtuple | listc                4    | \  }}}}||z
  }||z
  }||||z  fS )an  Calculate the dimensions and area of a bounding box.

        Args:
            bbox (tuple | list): Bounding box coordinates in the format (x_min, y_min, x_max, y_max).

        Returns:
            width (float): Width of the bounding box.
            height (float): Height of the bounding box.
            area (float): Area enclosed by the bounding box.

        Examples:
            >>> from ultralytics.utils.plotting import Annotator
            >>> im0 = cv2.imread("test.png")
            >>> annotator = Annotator(im0, line_width=10)
            >>> annotator.get_bbox_dimension(bbox=[10, 20, 30, 40])
        rd   )r[  x_miny_minx_maxy_maxr   heights          r3   get_bbox_dimensionzAnnotator.get_bbox_dimension  s5    $ &*"ueUfefn,,r5   )NNrg   Frh   )
ri   rj   rk   rj   rl   rV   rm   rM   rn   rV   )r   r>   )r   rO   r   rO   rN   rO   )r   r   r>   )r   rV   r   rO   r   rO   )Nr  F)r  r  r  r	  r
  rM   )r)  NTr+  N)
r   rO   r,  rj   r-  rM   r.  r	  r   r/  )NNrR   )r   rS   )r>   rD  rd   )r   rV   r   rO   rE  rV   rF  rO   r^   N)rN  rO  )rV  )rW  rV   )r[  r\  )r_   r`   ra   rb   rI   r   r  r!  r4  r   r   r   rM  rT  rZ  rc   rc  rd   r5   r3   rf   rf      sw        . "& $X
 X
 X
 X
 X
t    .; ; ; ; ;z0$ 0$ 0$ 0$ 0$j "! "&A$ A$ A$ A$ A$F6 6 6 6 6k k k k k<, , ,
= = = =
	! 	! 	! 	! 	!3 3 3 3 3 - - - \- - -r5   rf   rd   r   c           	        ddl m} ddl}ddlm} t          j        d|dz   d           t          |                                dz             }| dd         } |	                    | g d	
          }	|
                    dddg          }
|                    dddd          d                                         }|d                             |t          j        d||dz             dz
  d          }t!          |          D ]?}|d         j        |                             d t'          |          D                        @|d                             d           dt+          |          cxk     rdk     rn n|d                             t!          t+          |                               |d                             t1          |                                          dd           |d                             |d                    n|d                             d           t          j        d| ddddf         dz  z
  d| ddddf         dz  z   g          dz  } t;          j        t          j        dt          j                   d z            }tC          |dd!         | dd!                   D ]N\  }}tE          j#        |          $                    |%                                dt'          |          "           O|d         &                    |           |d         '                    d#           |d         (                    |	d$         |	d%         d&|
'           |d                             d$           |d                             d%           |d(         (                    |	d)         |	d*         d&|
'           |d(                             d)           |d(                             d*           d+D ]-}d,D ](}||         j)        |         *                    d-           ).|dz  }|+                    |d./           |,                                 |r ||           dS dS )0a  Plot training labels including class histograms and box statistics.

    Args:
        boxes (np.ndarray): Bounding box coordinates in format [x, y, width, height].
        cls (np.ndarray): Class indices.
        names (dict, optional): Dictionary mapping class indices to class names.
        save_dir (Path, optional): Directory to save the plot.
        on_plot (Callable, optional): Function to call after plot is saved.
    r   N)LinearSegmentedColormapzPlotting labels to z
labels.jpgz... rR   i@B )rv   yr   rb  )schema
white_bluewhitebluerQ   )r~   r~   Tfigsizetight_layoutr  皙?)binsrwidthc                    g | ]}|d z  S )r6   rd   r0   rv   s     r3   r4   zplot_labels.<locals>.<listcomp>N  s    ">">">q1s7">">">r5   	instances   Z   r   )rotationfontsizeclassesr\     )rz  rz  rp   r?   r6   i  r   offrv   rg  2   )rp  cmaprp   r   rb  >   r   rR   rQ   rp   >   rD  leftrightrH  F   dpi)-matplotlib.pyplotpyplotpolarsmatplotlib.colorsrf  r   inforS   r   	DataFrame	from_listsubplotsravelhistrD   linspacerangepatches	set_colorr   
set_ylabelrB   
set_xticksset_xticklabelsr   r  	bar_label
set_xlabelcolumn_stackr   r   onesrF   zipr   r   r   r   imshowaxishist2dspinesset_visiblesavefigclose)boxesclsnamessave_diron_plotpltr  rf  ncrv   subplot_3_4_coloraxrg  rJ   imgclass_idr   asfnames                       r3   plot_labelsr  3  st    $#####MMM999999 KCh&=CCCDDD	SWWYY]		B(7(OE'D'D'DEEA 099,RXHYZZ	aF	>	>q	A	G	G	I	IB
1

3R[BQ77#=c
JJA2YY @ @	!Q!!">">F1II">">">????qE[!!!3u::
1s5zz**+++
1d5<<>>22R"MMM
1!
1###OS5AaC=1#44cE!!!QqS&MA<M6MNOORVVE
/"'/BBBSH
I
ICS#Ydsd44 W W#s%%cjjll!VHEUEU%VVVVqELLqEJJuqELL33b/@LAAAqESqESqELL7Qx[r8ILJJJqEWqEX / /3 	/ 	/AqELO''....	/ |#EKK3KIIKKK  r5   zim.jpggRQ?r   FTfiler   gainr	  padrS   squarerM   BGRrZ  c                   t          | t          j                  st          j        |           } t	          j        |                     dd                    }|rC|ddddf                             d          d                             d          |ddddf<   |ddddf         |z  |z   |ddddf<   t	          j	        |          
                                } t	          j        | |j                  } |j        d         dk    }	|t          | d                   t          | d                   t          | d	                   t          | d
                   dd|s|	rdndf         }
|r|j                            dd           t!          t#          |                              d                    }|	r|
                    d          n|r|
ddddf         n|
}
t)          j        |
                              |dd           |
S )aM  Save image crop as {file} with crop size multiple {gain} and {pad} pixels. Save and/or return crop.

    This function takes a bounding box and an image, and then saves a cropped portion of the image according to the
    bounding box. Optionally, the crop can be squared, and the function allows for gain and padding adjustments to the
    bounding box.

    Args:
        xyxy (torch.Tensor | list): A tensor or list representing the bounding box in xyxy format.
        im (np.ndarray): The input image.
        file (Path, optional): The path where the cropped image will be saved.
        gain (float, optional): A multiplicative factor to increase the size of the bounding box.
        pad (int, optional): The number of pixels to add to the width and height of the bounding box.
        square (bool, optional): If True, the bounding box will be transformed into a square.
        BGR (bool, optional): If True, the image will be returned in BGR format, otherwise in RGB.
        save (bool, optional): If True, the cropped image will be saved to disk.

    Returns:
        (np.ndarray): The cropped image.

    Examples:
        >>> from ultralytics.utils.plotting import save_one_box
        >>> xyxy = [50, 50, 150, 150]
        >>> im = cv2.imread("image.jpg")
        >>> cropped_im = save_one_box(xyxy, im, file="cropped.jpg", square=True)
    r   r\   NrQ   rR   r   )r   rR   )r   rp   )r   r   )r   rQ   T)parentsexist_okz.jpg._   )qualitysubsampling)r   r   r   stackr   	xyxy2xywhviewr   r  	xywh2xyxylong
clip_boxesr   rS   parentmkdirrV   r   with_suffixsqueezer   r   rZ  )xyxyr   r  r  r  r  r  rZ  r   	grayscalecropfs               r3   save_one_boxr  n  s   F dEL)) !{4  diiA&&''A 3QQQU8<<??1%//22!!!QRR%ABBx$$AaaaeH=  ""D>$))Dq Ic$t*ooDJ/T$Z3tDz??1RTvTv]`XudmXuXYXYsuTvvwD A$666t$$008899#,Rt||BS2R$sDDbDy//d""1ba"@@@Kr5   )r   rp   r*  r*  r?   z
images.jpgi  rY   r+  labelsdict[str, Any]imagestorch.Tensor | np.ndarraypathslist[str] | Noner  rV   r  dict[int, str] | Noner  Callable | Nonemax_sizemax_subplotsr.  rN   np.ndarray | Nonec
           	       / dD ]}
|
| vr|
dk    r/| |
         j         dk    r| |
                             d          | |
<   t          | |
         t          j                  r/| |
                                                                         | |
<   |                     dt          j	        dt          j
                            }|                     dt          j	        |j        t          j
                            }|                     dt          j	        dt          j                            }|                     d	d
          }|                     dt          j	        dt          j                            }|                     dt          j	        dt          j                            }|                     d|          }t          |          rRt          |t          j                  r8|                                                                                                }|j        d         }|dk    r9t          j        |d
d
d
df                   }t          j        ||fd          }n|dk    r|d
d
d
df         }|j        \  }}}}t%          ||          }t          j        |dz            /t          j        |d                   dk    r|dz  }t          j        t-          /|z            t-          /|z            dfdt          j                  }t/          |          D ][}t-          ||/z  z            t-          ||/z  z            }}||                             ddd          ||||z   |||z   d
d
f<   \|/z  t)          ||          z  }|dk     r^t3          j        ||z            }t3          j        ||z            }t5          j        |t9          /fd||fD                                 }t-          ||z   /z  dz            }t)          |d          }t;          |t=          |dz            |dt?          |                    }t/          |          D ]}t-          ||/z  z            t-          ||/z  z            }}|                     ||||z   ||z   gd
dd           |r@|!                    |dz   |dz   gtE          ||                   j#        d
d         d           t          |          dk    ru||k    }||         $                    d          }|d
u } |||         nd
} t          |          r||         }!t          |!          rg|!d
d
d
df                                         d k    r)|!d!ddgfxx         |z  cc<   |!d!ddgfxx         |z  cc<   n|dk     r|!d!d
dfxx         |z  cc<   |!d"xx         |z  cc<   |!d#xx         |z  cc<   |!j        d$         dk    }"|"rtK          j&        |!          ntK          j'        |!          }!tQ          |!$                    t          j
                  )                                          D ]o\  }#}$||#         }tU          |          }%|r|                    ||          n|}| s| |#         |	k    r+| r| n| d%| |#         d&}&|+                    |$|&|%'           pnkt          |          r\|D ]Y}tU          |          }%|r|                    ||          n|}| r| n| d%| d         d&}&|!                    ||g|&|%d()           Zt          |          r||         ,                                }'t          |'          rh|'d"                                         d*k    s|'d#                                         d*k    r!|'d"xx         |z  cc<   |'d#xx         |z  cc<   n|dk     r|'|z  }'|'d"xx         |z  cc<   |'d#xx         |z  cc<   t/          t          |'                    D ]-}#| s| |#         |	k    r|-                    |'|#         |	+           .t          |          r'|j        d         |j        d         k    r!|                                dk    r	||         }(nn||g         }(|.                                })t          j/        d|)dz             0                    |)ddf          }*|(|*k    $                    t          j                  }(t          j1        |j2                  ,                                }+t/          t          |(                    D ]}#| s| |#         |	k    rtU          ||#                   }%|(|#         j        \  },}-|,|k    s|-|k    rW|(|#         $                    t          j                  }.t5          j        |.||f          }.|.$                    tf                    }.n |(|#         $                    tf                    }.	 |+|||z   |||z   d
d
f         |.         d,z  t          j4        |%          d-z  z   |+|||z   |||z   d
d
f         |.<   # tj          $ r Y w xY w |6                    |+           |st          j1        |j2                  S |j2        7                    |           |r ||           d
S d
S ).a  Plot image grid with labels, bounding boxes, masks, and keypoints.

    Args:
        labels (dict[str, Any]): Dictionary containing detection data with keys like 'cls', 'bboxes', 'conf', 'masks',
            'keypoints', 'batch_idx', 'img'.
        images (torch.Tensor | np.ndarray): Batch of images to plot. Shape: (batch_size, channels, height, width).
        paths (list[str] | None): List of file paths for each image in the batch.
        fname (str): Output filename for the plotted image grid.
        names (dict[int, str] | None): Dictionary mapping class indices to class names.
        on_plot (Callable | None): Callback function to be called after saving the plot.
        max_size (int): Maximum size of the output image grid.
        max_subplots (int): Maximum number of subplots in the image grid.
        save (bool): Whether to save the plotted image grid to a file.
        conf_thres (float): Confidence threshold for displaying detections.

    Returns:
        (np.ndarray | None): Plotted image grid as a numpy array if save is False, None otherwise.

    Notes:
        This function supports both tensor and numpy array inputs. It will automatically
        convert tensor inputs to numpy arrays for processing.

        Channel Support:
        - 1 channel: Grayscale
        - 2 channels: Third channel added as zeros
        - 3 channels: Used as-is (standard RGB)
        - 4+ channels: Cropped to first 3 channels
    >   r  r<  r!  bboxesr  	batch_idx	keypointsr  rQ   rR   r   r?   r  r  r<  Nr!  r  r  )r  rp   r  r6   c              3  <   K   | ]}t          |z            V  d S rd  rZ   )r0   rv   nss     r3   r[   zplot_images.<locals>.<genexpr>  s-      )F)F!#a"f++)F)F)F)F)F)Fr5   g{Gz?   r   T)ri   rk   rm   rn   r>   )r   r   (   )   r  r  )r   r   rS   r\   g?.).r   ).rR   r    z.1f)r   )@   r  r  r7   )r   rF  g)\(?)r.  g?g333333?)8r6  r  r   r   r   r  r  getrD   zerosint64r   r  rF   rB   r	  r   concatenateminr3  r   fullrS   r  	transposemathr   resizerO   rf   r   rV   r   r   r   namer  r   xywhr2xyxyxyxyr  r  r   r   r  r   r4  r   arangereshaper   r   rM   rE   r   r   rZ  )0r  r  r  r  r  r  r  r  rZ  r.  r8  r  r  r  confsr!  r4  r1   zerobs_rU   r  mosaicrJ   rv   rg  scalefs	annotatoridxry  r<  r  is_obbjr   r   r   kpts_image_masksnlindexr   mhmwr#  r  s0                                                  @r3   plot_imagesr    s    R T 0 0F??::&).A--q	))!,,F1IfQi.. 	0q	--//F1I
**UBHQbh777
8
8C

;"((K(K(KLLIZZ"(1BJ"?"?"?@@FJJvt$$EJJw"( ; ; ;<<E::k28ARZ#@#@#@AADZZv&&F
6{{ .z&%,77 .##%%++-- 	QAAvv}VAAArrE]++Q777	
Q2A2,KB1a	R		B	S		B	vfQiA# Wc"q&kk3rAv;;2CrxHHHF2YY G G1R=!!3qAF|#4#41*0)*=*=aA*F*Fq1q5y!a!e)QQQ&'' rMC1II%EqyyIeai  Ieai  FE)F)F)F)F1v)F)F)F$F$FGG 
a!er\D 	!	!B	RB&U27^^rt]`af]g]ghhhI2YY P( P(1R=!!3qAF|#4#41Q1q5!a%0$qQQQ 	eNNAE1q5>U1X0CCRC0HTcNddds88a<<q.C#hooe,,Gd]F!&!25::D6{{ `su:: 0QQQU|''))S00cAq6k***a/***cAq6k***a/****c2A2g%/f"f"RA-5;U*5111uAUAU'RX(>(>(E(E(G(GHH E EFAs
A"1IIE+07		!QaA Ea:!5!5*0 J16J6JT!W6J6J6J!++Ce+DDDE W `  ` `A"1IIE+07		!QaA&,FqFFQ2F2Fa2F2F2FENNAq65EM^N____ 4yy HS	((u:: 'V}((**d22eFm6G6G6I6IT6Q6Qf*f*f"f"s5zz** H HA Ha:!5!5!uQxJGGG 5zz (9Q<5;q>11eiikkQ6F6F"'*KK"'*KBIaa0088"aDDE#.%#7"?"?
"K"KKZ	--2244s;//00 ! !A !a:!5!5 &wqz 2 2!,Q!5B77bAgg#.q>#8#8#B#BD#&:dQF#;#;D#';;t#4#4DD#.q>#8#8#>#>D! "1q1u9a!a%i#: ;D AC G"(SX//\_J_ _ q1q5y!a!e)QQQ67==  ) ! ! ! D! "6 ##B''' (z),'''Le  s   Ai  
i.-i.path/to/results.csvdirc           
     |   ddl m} ddl}ddlm} | rt          |           j        nt          |          }t          |                    d                    }t          |          s J d|
                                 d            g g }	}t          |          D ]G\  }
}	 |                    |d          }|
dk    r|j        D ]5}d|v r|                    |           d	|v r|	                    |           6t          |          d
z  t          |	          d
z  }}|d|         |	d|         z   ||d         z   |	|d         z   }|                    d
t          |          d
z  t          |          d
z   dfd          \  }}|                                }|                    |j        d                                                                                   }t          |          D ]\  }
}|                    |                                                                                              d          }||
                             ||d|j        d
d           ||
                             | ||d          ddd
           ||
                             |d           # t0          $ r%}t3          j        d| d|            Y d}~Ad}~ww xY w|d                                          |dz  }|                    |d           |                                 |r ||           dS dS )a  Plot training results from a results CSV file. The function supports various types of data including
    segmentation, pose estimation, and classification. Plots are saved as 'results.png' in the directory where the
    CSV is located.

    Args:
        file (str, optional): Path to the CSV file containing the training results.
        dir (str, optional): Directory where the CSV file is located if 'file' is not provided.
        on_plot (Callable, optional): Callback function to be executed after plotting. Takes filename as an argument.

    Examples:
        >>> from ultralytics.utils.plotting import plot_results
        >>> plot_results("path/to/results.csv")
    r   Ngaussian_filter1dzresults*.csvzNo results.csv files found in z, nothing to plot.infer_schema_lengthlossmetricrQ   r|   Trl  r	  .r~   )markerr   	linewidth
markersizerp   sigma:smoothr   r	  rs   )rx  zPlotting error for z: rR   zresults.pngr  r  )r  r  r  scipy.ndimager  r   r  r   globrB   resolver  read_csvcolumnsappendr  r  selectto_numpyflattenr  plotstem	set_titler   r   errorlegendr  r  )r  r  r  r  plr  r  files	loss_keysmetric_keysrJ   r  r   r1   loss_mid
metric_midr  figr  rv   r  rg  rU  r  s                           r3   plot_resultsr%  W  s    $#####//////$(7tDzz  d3iiH~..//Eu::^^^8H8H8J8J^^^^^:{I%   9 91	9;;qd;;;DAvv . .A{{!((++++!Q#**1---'*9~~':C<L<LPQ<Q*ixi(;{
{+CCiPXPYPYFZZ]hisitit]uu  ,,q#g,,!*;c'llUVFVXYEZim,nnRXXZZDLO,,5577??AAA!'** 0 01KKNN++--5577>>wGG1

1a16QST
UUU1

1//;;;S\]
^^^1B////	0
  	9 	9 	9L7q77A7788888888	9qELLNNN}$EKK3KIIKKK  s   !HJ11
K ;KK    viridisro  nonerp  r}  r  
edgecolorsc                    	
 ddl m} t          j         |          \  	
 	
fdt	          t                               D             }|                     ||||           dS )a)  Plot a scatter plot with points colored based on a 2D histogram.

    Args:
        v (array-like): Values for the x-axis.
        f (array-like): Values for the y-axis.
        bins (int, optional): Number of bins for the histogram.
        cmap (str, optional): Colormap for the scatter plot.
        alpha (float, optional): Alpha for the scatter plot.
        edgecolors (str, optional): Edge colors for the scatter plot.

    Examples:
        >>> v = np.random.rand(100)
        >>> f = np.random.rand(100)
        >>> plt_color_scatter(v, f)
    r   N)rp  c                   g | ]}t          t          j        |         d           dz
  j        d         dz
            t          t          j        |         d           dz
  j        d         dz
            f         S )T)r  rR   r   )r  rD   digitizer   )r0   rJ   r  r  vxedgesyedgess     r3   r4   z%plt_color_scatter.<locals>.<listcomp>  s       
 	 	AaD&55594:a=1;LMMAaD&55594:a=1;LMMO	
  r5   )r1   r}  r  r)  )r  r  rD   histogram2dr  rB   scatter)r-  r  rp  r}  r  r)  r  r   r  r.  r/  s   ``      @@@r3   plt_color_scatterr2    s      $##### >!QT:::D&&       
 s1vv  F KK1T:KNNNNNr5   tune_results.csvcsv_fileexclude_zero_fitness_pointsc                   ddl m ddl}ddlm} fd}t          |           } |                    | d          }d}d |j        D             |d         }|                                }|dddf         }	|r|	dk    }
||
         |	|
         }	}t          |	          dk    rt          j        d           dS t          d	          D ]^}|	                                |	                                }}|d	|z  z
  }|	|k    }
|
                                r n||
         |	|
         }	}_t!          j        |	          }t%          j        t          |          d
z            }                    dd           t+          |          D ]\  }}|dd||z   f         }||         }                    |||dz              t/          ||	ddd                               ||	                                dd                               | d|dddi                               dd           ||z  dk    r                    g             ||                     d                     t          dt          |	          dz             }                    dd                               ||	ddd !                               | ||	d	"          d#d$d%&                               d'                               d(                               d)                                d           !                                  ||                     d*                     dS )+a	  Plot the evolution results stored in a 'tune_results.csv' file. The function generates a scatter plot for each
    key in the CSV, color-coded based on fitness scores. The best-performing configurations are highlighted on
    the plots.

    Args:
        csv_file (str, optional): Path to the CSV file containing the tuning results.
        exclude_zero_fitness_points (bool, optional): Don't include points with zero fitness in tuning plots.

    Examples:
        >>> plot_tune_results("path/to/tune_results.csv")
    r   Nr  c                                         | d                                            t          j        d|             dS )z#Save one matplotlib plot to 'file'.r  r  zSaved N)r  r  r   r  )r  r  s    r3   _save_one_filez)plot_tune_results.<locals>._save_one_file  sB    Dc"""		OTOO$$$$$r5   r  rR   c                6    g | ]}|                                 S rd   )striprs  s     r3   r4   z%plot_tune_results.<locals>.<listcomp>  s     ,,,!AGGII,,,r5   z@No valid fitness values to plot (all iterations may have failed)rp   r  )r   r   Trl  r'  ro  r(  )r}  r  r)  zk+rz   )r
  z = z.3gr   r   )fontdictbothr~   )r  	labelsizeztune_scatter_plots.png)r   r|   ofitness)r  	linestyler   r  r  smoothedrQ   r  zFitness vs Iteration	IterationFitnessztune_fitness.png)"r  r  r  r  r  r   r  r  r  rB   r   rS  r  meanstdallrD   argmaxr  r3  figurer  subplotr2  r  r   rN  tick_paramsyticks	with_namexlabelylabelgridr  )r4  r5  r  r  r8  r   num_metrics_columnskeysrv   r?  r#  r  rD  rE  lower_boundr  rC   rJ   r8  r-  mur  s                        @r3   plot_tune_resultsrT    s    $#####//////% % % % % H~~H;;xT;::D,,t|,,,-@-A-ABDA1gG" ,{tWgdm7
7||qYZZZ1XX , ,LLNNGKKMMcQWn+%88:: 	EtWgdm7
	'A	#d))s"##AJJxdJ333$ 	 	1aaa((()qTAq!a%   !W9CFSSSSW[[]]DR888		Q##2###vqk	:::Vq111q5A::JJrNNNN8%%&>??@@@ 	aW!""AJJwTJ222HHQvYHGGGHHQ!!'333S
VWHXXXII$%%%JJ{JJyHHTNNNJJLLLN8%%&899:::::r5       zruns/detect/expmodule_typestagerC   r  c           	     2   ddl m} dD ]	}||v r dS 
t          | t          j                  r| j        \  }}}	}
|	dk    r|
dk    r|d| d|                    dd          d          d	z  }t          j        | d                                         |d
          }t          ||          }|
                    t          j        |dz            dd          \  }}|                                }|                    dd           t          |          D ]P}||                             ||                                                    ||                             d           Qt'          j        d| d| d| d           |                    |dd           |                                 t/          j        t3          |                    d                    | d                                                                                    dS dS dS dS )ab  Visualize feature maps of a given model module during inference.

    Args:
        x (torch.Tensor): Features to be visualized.
        module_type (str): Module type.
        stage (int): Module stage within the model.
        n (int, optional): Maximum number of feature maps to plot.
        save_dir (Path, optional): Directory to save results.
    r   N>   OBBPoseDetectSegmentClassifyRTDETRDecoderrR   rW  r  r  r   z_features.pngr  r~   T)rn  g?)wspacehspacer{  zSaving z... (/)i,  tight)r  bbox_inchesz.npy)r  r  r   r   r   r   rsplitchunkr  r  r  r  r3  r  subplots_adjustr  r  r  r  r   r  r  r  rD   rZ  rV   r  r  )rv   rV  rW  rC   r  r  mr  channelsrb  r   r  blocksr  rJ   s                  r3   feature_visualizationrk    s#    $#####N  FF !U\"" D%&W"8VUA::%!))X5XX;+=+=c1+E+Eb+IXXXXA[1X1===FAx  ALL1q5!1!114LHHEArBtD9991XX " "1VAY..001111

5!!!!K9!99!99h999:::KKsK888IIKKKGCf--..!

0@0@0B0BCCCCC#D D:))r5   )r  r   r  r	  r  rS   r  rM   r  rM   rZ  rM   )r  r  r  r  r  r  r  rV   r  r  r  r  r  rS   r  rS   rZ  rM   r.  r	  rN   r  )r  r   N)r  rV   r  rV   r  r  )r&  r'  ro  r(  )rp  rS   r}  rV   r  r	  r)  rV   )r3  T)r4  rV   r5  rM   )rV  rV   rW  rS   rC   rS   r  r   )-
__future__r   r  collections.abcr   pathlibr   typingr   r   r  rD   r   PILr   r   r	   r
   r   ultralytics.utilsr   r   r   r   r   r   r   ultralytics.utils.checksr   r   r   ultralytics.utils.filesr   r   r   rf   r  r  r  r  r  r%  r2  rT  rk  rd   r5   r3   <module>rt     s%   # " " " " "  $ $ $ $ $ $             



      + + + + + + + + + + * * * * * * a a a a a a a a a a a a a a a a a a H H H H H H H H H H 2 2 2 2 2 2MG MG MG MG MG MG MG MG` 
H- H- H- H- H- H- H- H-V "$ttBxx 6 6 6  6x h3 3 3 3 3l 
 )11A(T(T(T"#'#o o o o 
od 3 3 3 3 3lO O O O O@ D; D; D; D; D;N DFY]Y]^oYpYp  D  D  D  D  D  D  Dr5   