
    |hC                     
   d dl Z d dlZd dlmZ d dlmZmZmZmZm	Z	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dede'de(de)de)de)fdZ*e ejV                  dejX                        dddddd dd!f	d"ee-ef   d#e
ej\                  ej^                  f   d$e	ee-      d%e-d&e	ee(e-f      d'e	e   d(e(d)e(de)d*e'd+e	ej^                     fd,       Z0 e       	 	 	 	 	 	 d@de-d-e-d.e)d/e)d0e)d'e	e   fd1       Z1dAd2e(d3e-d4e'd5e-fd6Z2dBd7e-fd8Z3d9 ed:      fd;e-d<e(d=e(d>efd?Z4y)C    N)Path)AnyCallableDictListOptionalUnion)Image	ImageDraw	ImageFont)__version__)IS_COLAB	IS_KAGGLELOGGER	TryExceptopsplt_settingsthreaded)
check_fontcheck_versionis_ascii)increment_pathc                   F    e Zd ZdZd Zd
dededefdZe	de
defd       Zy	)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.

    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)

    ## 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.
    c                 `   d}|D cg c]  }| j                  d|        c}| _        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                        | _        yc c}w )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A2FF0B#)      r   )r1      3   )r1      f   )   r7   r   )r1   r3   r1   )r3      r1   )r1   r6   r1   )r1   r4   r1   )r6   r5   r1   )r4   r3   r1   )r1   r3   r3   )r1   r6   r6   )r1   r4   r4   )r3   r1   r3   )r6   r1   r6   )r4   r1   r4   )r   r1   r   )r   r   r1   )r1   r   r   r1   r1   r1   dtypeN)hex2rgbpalettelennnparrayuint8pose_palette)selfhexscs      Y/var/www/html/test/engine/venv/lib/python3.12/site-packages/ultralytics/utils/plotting.py__init__zColors.__init__]   s    
, 8<<!qW-<T\\"HH), ((/
 =s   B+ibgrreturnc                 p    | j                   t        |      | j                  z     }|r|d   |d   |d   fS |S )z
        Convert hex color codes to RGB values.

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

        Returns:
            (tuple): RGB or BGR color tuple.
              r   )r=   intr?   )rD   rI   rJ   rF   s       rG   __call__zColors.__call__   s>     LLQ$&&)%(!adAaD!/a/    hc                 ,     t         fddD              S )z?Convert hex color codes to RGB values (i.e. default PIL order).c              3   N   K   | ]  }t        d |z   d |z   dz    d        yw)rN   rM      NrO   ).0rI   rR   s     rG   	<genexpr>z!Colors.hex2rgb.<locals>.<genexpr>   s+     FqS1q51q519-r2Fs   "%)r   rM      )tuple)rR   s   `rG   r<   zColors.hex2rgb   s     FIFFFrQ   N)F)__name__
__module____qualname____doc__rH   rO   boolrZ   rP   staticmethodstrr<    rQ   rG   r   r      sO    GR2
h0# 0D 0U 0 G3 G5 G GrQ   r   c                   *   e Zd ZdZ	 	 	 	 	 d&dee   dee   dededef
dZd'd	e	d
e	de	fdZ
d(ded	e	d
e	fdZd)dedefdZ	 	 	 	 	 d*de	dee   dededee	   f
dZd+defdZd,ded
e	dede	fdZd Zd Zd-d ee   fd!Zd.d"efd#Zed-d$ee	   fd%       Zy)/	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 (float): Line width for drawing.
        skeleton (List[List[int]]): Skeleton structure for keypoints.
        limb_color (List[int]): Color palette for limbs.
        kpt_color (List[int]): 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
line_width	font_sizefontpilexamplec                 X    t        |       }t        |t        j                        }|xs |xs | _        |xs< t	        t        t        |r|j                  n|j                        dz  dz        d       _	        |se|j                  d   dk(  r%t        j                  |t        j                        }n.|j                  d   dkD  rt        j                  |dddf         } j                  r|r|nt        j                  |       _         j                   j"                  dvr  j                   j%                  d       _        t'        j(                   j                   d	       _        	 t-        |rd
n|      }|xs8 t	        t        t         j                   j                        dz  dz        d      }	t/        j0                  t3        |      |	       _        t;        t<        d      r fd j4                  _        n||j@                  jB                  sJ d       |jD                  jF                  r|n|jI                          _        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 _'        tP        jR                  g d    _*        tP        jR                  g d    _+        h d _,        h d  _-        y# t6        $ r t/        j8                          _        Y Mw xY w)!zjInitialize the Annotator class with image and line width along with color palette for keypoints and limbs.rM   g~jth?rN      .N>   RGBRGBArl   rm   zArial.Unicode.ttfgQ?   z9.2.0c                 @    j                   j                  |       dd S )NrM   rY   )rg   getbbox)xrD   s    rG   <lambda>z$Annotator.__init__.<locals>.<lambda>   s    dii.?.?.B1Q.G rQ   zOImage not contiguous. Apply np.ascontiguousarray(im) to Annotator input images.rU                        	   
      rY      )rz   rz   rz   rz   rx   rx   rx   r   r   r   r   r   rU   rU   rU   rU   rU   rU   rU   )rU   rU   rU   rU   rU   r   r   r   r   r   r   rz   rz   rz   rz   rz   rz   >	   r      r8   r|   r1      D      r      r1   rN         r      o   r1         r|   r   r   r   r1   r1   r   >   r      &   /   m      O   r   r1   h   r   {   l      r1      r   r   r1   r      r1   $   }   r1   *   rY   r1      r   r      rt   ).r   
isinstancer
   rh   maxroundsumsizeshapelwcv2cvtColorCOLOR_GRAY2BGRr@   ascontiguousarray	fromarrayimmodeconvertr   Drawdrawr   r   truetypera   rg   	Exceptionload_defaultr   pil_versiongetsizedata
contiguousflags	writeablecopytfsfskeletoncolorsrC   
limb_color	kpt_colordark_colorslight_colors)
rD   r   re   rf   rg   rh   ri   	non_asciiinput_is_pilr   s
   `         rG   rH   zAnnotator.__init__   s    !))	!"ekk23)3|eE#bgg288*TWX*X[`*`$acd exx{a\\"c&8&89!q))"S"1"W+688(beoob.ADGww||?2''//%0!tww7DI5!"5M QCc$'',,.?!.Ce.K(Lb$Q%..s4y$?	 ['2$G		!77%%x'xx%HH..bBGGIDG$''A+q)DGggkDG HHHHHGGFFFGGFFFFFFF'
, !--.no,,-ef


]  5%224	5s   ,A/L "L)(L)color	txt_colorrK   c                 B    || j                   v ry|| j                  v ry|S )aE  
        Assign text color based on background color.

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

        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   r9   )r   r   )rD   r   r   s      rG   get_txt_colorzAnnotator.get_txt_color  s,    " D$$$d''' rQ   labelc           
         | j                  ||      }t        |t        j                        r|j	                         }t        |d   t
              }|r|d   D cg c]  }t        |       c}nt        |d         t        |d         f}| j                  r^|r?| j                  j                  |D cg c]  }t        |       c}| j                  |      n'| j                  j                  || j                  |       |r| j                  j                  |      \  }}	|d   |	k\  }
|d   | j                  j                   d   |z
  kD  r!| j                  j                   d   |z
  |d   f}| j                  j                  |d   |
r|d   |	z
  n|d   |d   |z   dz   |
r|d   dz   n
|d   |	z   dz   f|       | j                  j#                  |d   |
r|d   |	z
  n|d   f||| j                         yy|rGt%        j&                  | j                  t)        j*                  |t              gd|| j                        nVt%        j                  | j                  |t        |d         t        |d	         f|| j                  t$        j,                  
       |r1t%        j.                  |d| j0                  | j2                        d   \  }}	|	d	z  }	|d   |	k\  }
|d   | j                  j4                  d   |z
  kD  r!| j                  j4                  d   |z
  |d   f}|d   |z   |
r|d   |	z
  n|d   |	z   f}t%        j                  | j                  |||dt$        j,                         t%        j6                  | j                  ||d   |
r|d   dz
  n
|d   |	z   dz
  fd| j0                  || j2                  t$        j,                  
       yyc c}w c c}w )a  
        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 (B, G, R).
            txt_color (tuple, optional): The color of the text (R, G, B).

        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   rN   widthoutlinefillr   rg   r:   TrM   rk   	thicknesslineType	fontScaler   N)r   r   torchTensortolistlistrO   rh   r   polygonrZ   r   	rectanglerg   r   r   r   textr   	polylinesr@   asarrayLINE_AAgetTextSizer   r   r   putText)rD   boxr   r   r   multi_pointsbp1wrR   outsidep2s               rG   	box_labelzAnnotator.box_label.  ss     &&ui8	c5<<(**,C!#a&$/)5c!f%c!f%CAKSQRV;U88  II#&'aq'tww  #'99#6#6s$''SX#6#Yyy((/1Q%1*a5477<<?Q..a1,be3B		##UBqEAIbeRUQY]Y`BqETUIfhijfknoforsfst $ 
 		1Gr!uqyAGU^eieneno   MM"**S45tUDGG#&==c#a&k3s1v;7$''\_\g\g$ ua477dggVWXY1QQ%1*a5477==+a//q)A-r!u4BUQYW1	"Q%!)Cdggr2ub#++FGGUBqEAIbeai!mDGG"gg [[	 - & (s   O
2Oalpharetina_masksc                 V   | j                   r2t        j                  | j                        j	                         | _        t        |      dk(  rM|j                  ddd      j                         j                         j                         dz  | j                  dd |j                  |j                  k7  r|j                  |j                        }t        j                  ||j                  t        j                        dz  }|ddddf   }|j                  d      }|||z  z  }d||z  z
  j!                  d      }|j#                  d	      j$                  }|j'                  dg
      }|j                  ddd      j                         }||d   z  |z   }|dz  }	|	j)                         j                         j                         }
|r|
n)t+        j,                  |
| j                  j.                        | j                  dd | j                   r| j1                  | j                         yy)a  
        Plot masks on image.

        Args:
            masks (torch.Tensor): Predicted masks on cuda, shape: [n, h, w]
            colors (List[List[int]]): Colors for predicted masks, [[r, g, b] * n]
            im_gpu (torch.Tensor): Image is in cuda, 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.
        r   rN   rM   r1   N)devicer;   g     o@rk   dim)dimsr   )rh   r@   r   r   r   r>   permuter   cpunumpyr   tor   tensorfloat32	unsqueezecumprodr   valuesflipbyter   scale_imager   r   )rD   masksr   im_gpur   r   masks_colorinv_alpha_masksmcsim_mask
im_mask_nps              rG   r  zAnnotator.masksl  s    88jj)..0DGu:?1a0;;=AACIIKcQDGGAJ==ELL(YYu||,FfU\\ORWW4&"v~.uu},55a8oo!o$++1#&1a(335/"--33,\\^'')//1
#/ZS__ZQUQXQXQ^Q^5_
88NN477# rQ   r   radiuskpt_line
conf_thresr   c                    ||n| j                   }| j                  r2t        j                  | j                        j                         | _        |j                  \  }}|dk(  xr |dv }	||	z  }t        |      D ]  \  }
}|xs* |	r| j                  |
   j                         n
t        |
      }|d   |d   }}||d   z  dk7  sJ||d   z  dk7  sVt        |      dk(  r|d   }||k  rot        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(  r%||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t        j"                  | j                  |||xs | j$                  |
   j                         t        t        j&                  | j                   dz              t        j                  
       ` | j                  r| j)                  | j                         yy)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 (B, G, R).

        Note:
            - `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.
        Nrt   >   rM   rk   r   rN   rk   rM   r   )r   r   )r   rh   r@   r   r   r   r   	enumerater   r   r   r>   r   circlerO   r   r   liner   ceilr   )rD   kptsr   r  r  r  r   nkptndimis_poserI   kcolor_kx_coordy_coordconfskpos1pos2conf1conf2s                        rG   r  zAnnotator.kpts  s   2 "-47788jj)..0DGZZ
d"*/GdO 	mDAqY'DNN1$5$<$<$>vVWyG tQqTWGq!Q&7U1X+=+Bq6Q;Q4Dj( 

477S\3w<$@&'SU`c`k`kl	m ::b>D"4==1 2D"Q%!)a013tRUQYN7K3LMD"Q%!)a013tRUQYN7K3LM19 "Q%!)a0E "Q%!)a0Ez)UZ-? 7U1X%*d1ga.@A.EaSTX\]^X_bcXc7U1X%*d1ga.@A.EaSTX\]^X_bcXcGG<!3!:!:!<!"''$''A+"67 [[( 88NN477# rQ   r   c                 @    | j                   j                  ||||       y)z"Add rectangle to image (PIL-only).N)r   r   )rD   xyr   r   r   s        rG   r   zAnnotator.rectangle  s    		Bgu5rQ   r   anchor	box_colorc           
      |   | j                   r| j                  j                  |      \  }}|dk(  r|dxx   d|z
  z  cc<   |j                  d      D ]  }|rW| j                  j                  |      \  }}| j                  j                  |d   |d   |d   |z   dz   |d   |z   dz   f|       | j                  j                  |||| j                         |dxx   |z  cc<    y|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                  
       y)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 (R, G, B).
            anchor (str, optional): Text anchor position ('top' or 'bottom').
            box_color (tuple, optional): Box color (R, G, B, A) with optional alpha.
        bottomrN   
r   r   r   r   rk   r   r   N)rh   rg   r   splitr   r   r   r   r   r   r   r   r   r   )rD   r*  r   r   r+  r,  r   rR   r  r   r   s              rG   r   zAnnotator.text  s    8899$$T*DAq!1Q

4( 99,,T2DAqII''A1r!uqy1}beaiRSm(T[d'e		r4idiiH1
 tQ$''TWWUVWX1QQ%1*UQYW1	"Q%!)Cdggr2y"ckkJKKr1dggyDGG^a^i^ijrQ   c                     t        |t        j                        r|nt        j                  |      | _        t	        j
                  | j                        | _        y)z"Update self.im from a numpy array.N)r   r
   r   r   r   r   r   )rD   r   s     rG   r   zAnnotator.fromarray  s5    "2u{{3"9LNN477+	rQ   c                 @    t        j                  | j                        S )z Return annotated image as array.)r@   r   r   )rD   s    rG   resultzAnnotator.result  s    zz$''""rQ   titlec                 *   t        j                  t        j                  | j                        ddddf         }t
        st        r	 t        |       y|j                  |       y# t        $ r"}t        j                  d|        Y d}~yd}~ww xY w)zShow the annotated image..Nr   z.Unable to display image in Jupyter notebooks: )r4  )r
   r   r@   r   r   r   r   displayImportErrorr   warningshow)rD   r4  r   es       rG   r9  zAnnotator.show   sx    __RZZ0dd;<yU GG%G   U!OPQsSTTUs   A' '	B0BBfilenamec                 j    t        j                  |t        j                  | j                               y)z'Save the annotated image to 'filename'.N)r   imwriter@   r   r   )rD   r;  s     rG   savezAnnotator.save  s    Hbjj12rQ   bboxc                 4    | \  }}}}||z
  }||z
  }||||z  fS )ap  
        Calculate the dimensions and area of a bounding box.

        Args:
            bbox (tuple): 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])
        rb   )r?  x_miny_minx_maxy_maxr   heights          rG   get_bbox_dimensionzAnnotator.get_bbox_dimension  s5    & &*"ueUfefn,,rQ   )NNz	Arial.ttfFabc)r2   r2   r2   r9   ) rH  r9   )      ?F))  rK  NT      ?N)NNrN   )r9   toprb   N)z	image.jpg)r[   r\   r]   r^   r   rO   ra   r_   rH   rZ   r   r   floatr  r  r   r   r   r3  r9  r>  r`   rF  rb   rQ   rG   rd   rd      sx   0 %)#'V
 SMV
 C=	V

 V
 V
 V
p5 u ch 0<C <U <Y^ <|"$% "$T "$N " $ %)B$ B$ 	B$
 B$ B$ E?B$H6C 6kS kU kc kfk k>,
#	!(3- 	!3S 3 -% - -rQ   rd   rb   rI  c           
      H   ddl m} ddl}ddlm} t        j                  dt        d       t        j                  dt               t        j                  d|d	z   d
       t        |j                         dz         }| dd } |j                  | g d      }		 ddl}
|
j                  |	dddt!        d      t!        d             |j#                  |dz  d       |j%                          |j)                  dddg      }|j+                  dddd      d   j-                         }|d   j/                  |t1        j2                  d||dz         d z
  d!"      }t5        |      D ]=  }|d   j6                  |   j9                  t;        |      D 	cg c]  }	|	d#z  	 c}	       ? |d   j=                  d$       dt?        |      cxk  rd%k  rXn nU|d   jA                  t5        t?        |                   |d   jC                  tE        |jG                               d&d'(       n|d   jI                  d)       t1        jJ                  d | dddd*f   dz  z
  d | dddd*f   dz  z   g      d+z  } tM        jN                  t1        jP                  d,t0        jR                  -      d#z        }tU        |dd. | dd.       D ]5  \  }}tW        jX                  |      j[                  |dt;        |      /       7 |d   j]                  |       |d   j_                  d0       |d   ja                  	d1   |	d2   d|3       |d   jI                  d1       |d   j=                  d2       |d4   ja                  |	d5   |	d6   d|3       |d4   jI                  d5       |d4   j=                  d6       d7D ]*  }d8D ]#  }||   jb                  |   je                  d9       % , |d	z  }|j#                  |d       |j%                          |r	 ||       yy# t&        $ r Y +w xY wc c}	w ):a  
    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)LinearSegmentedColormapignorez&The figure layout has changed to tight)categorymessage)rS  zPlotting labels to z
labels.jpgz... rN   i@B )rq   yr   rE  )columnsTautohist2   binsg?)pmax)corner	diag_kindkinddiag_kwsplot_kwszlabels_correlogram.jpg   dpi
white_bluewhitebluerM   )ry   ry   figsizetight_layoutrJ  皙?)r[  rwidthr1   	instances   Z   r{   )rotationfontsizeclassesrY     )rs  rs  rk   r:   i  r   offrq   rU  )r[  cmaprk   r   rE  >   r   rN   rM   rk   >   rM  leftrightr.  F)3matplotlib.pyplotpyplotpandasmatplotlib.colorsrQ  warningsfilterwarningsUserWarningFutureWarningr   inforO   r   	DataFrameseabornpairplotdictsavefigcloser7  	from_listsubplotsravelrX  r@   linspacerangepatches	set_colorr   
set_ylabelr>   
set_xticksset_xticklabelsr   r  
set_xlabelcolumn_stackr
   r   onesrB   zipr   r   r   imshowaxishist2dspinesset_visible)boxesclsnamessave_diron_plotpltrz  rQ  ncrq   r  subplot_3_4_coloraxrU  rI   imgr   asfnames                       rG   plot_labelsr  (  s    $9 H{DlmH}= KK%h&=%>dCD	SWWY]	B(7OE(EFA46QU[]Q^imsviwxH77SA		
 099,RXHYZ	aF	>q	A	G	G	IB
1

3R[[BQ7#=c
JA2Y @	!Q!!F1I">q1s7">?@qE[!3u:
1s5z*+
1d5<<>2R"M
1#OOS5AaC=1#44cE!QqS&MA<M6MNORVVE
//"''/BSH
ICDS	5#;/ ISs%%cF3K%HIqELLqEJJuqELL33b/@LAqESqESqELL7Qx[r8ILJqEWqEX /3 	/AqELLO''.	// |#EKK3KIIK G   #?s   AP P
	PPzim.jpggRQ?r{   FTfilegainpadsquareBGRr>  c                    t        | t        j                        st        j                  |       } t	        j
                  | j                  dd            }|r5|ddddf   j                  d      d   j                  d      |ddddf<   |ddddf   |z  |z   |ddddf<   t	        j                  |      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                  j                  dd       t!        t#        |      j%                  d            }|	r|
j'                  d      n|r
|
ddddf   n|
}
t)        j*                  |
      j-                  |dd       |
S )aR  
    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   rY   NrM   rN   r   )r   rN   )r   rk   )r   r   )r   rM   T)parentsexist_okz.jpg._   )qualitysubsampling)r   r   r   stackr   	xyxy2xywhviewr   r  	xywh2xyxylong
clip_boxesr   rO   parentmkdirra   r   with_suffixsqueezer
   r   r>  )xyxyr   r  r  r  r  r  r>  r   	grayscalecropfs               rG   save_one_boxr  p  s   H dELL){{4 diiA&'AQU8<<?1%//2!QR%ABx$$AaeH==  "D>>$)Dq Ic$t*oDJ/T$Z3tDz?1RTv]`dmXYsuTvvwD$6t$0089#,t||BS$sDbDy/d""1ba"@KrQ   )r   rk   rK  rK  r:   z
images.jpgi  rU   rL  labelsimagespathsr  r  r  max_sizemax_subplotsr  rK   c
           	      n  . dD ]w  }
|
| vr|
dk(  r)| |
   j                   dk(  r| |
   j                  d      | |
<   t        | |
   t        j                        sT| |
   j                         j                         | |
<   y | j                  dt        j                  dt        j                              }| j                  dt        j                  |j                  t        j                              }| j                  dt        j                  dt        j                              }| j                  d	d
      }| j                  dt        j                  dt        j                              }| j                  dt        j                  dt        j                              }| j                  d|      }t        |      rFt        |t        j                        r,|j                         j                         j                         }|j                  d   dkD  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 ]L  }t)        ||.z  z        t)        ||.z  z        }}||   j-                  ddd      ||||z   |||z   d
d
f<   N |.z  t%        ||      z  }|dk  rZt/        j"                  ||z        }t/        j"                  ||z        }t1        j2                  |t5        .fd||fD                    }t)        ||z   .z  dz        }t%        |d      }t7        |t9        |dz        |dt;        |            }t+        |      D ]  }t)        ||.z  z        t)        ||.z  z        }}|j=                  ||||z   ||z   gd
dd       |r5|j?                  |dz   |dz   gtA        ||         jB                  d
d d       t        |      dkD  s||k(  }||   jE                  d      }|d
u } t        |      rZ||   }|||   nd
}t        |      rU|d
d
d
df   j%                         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tG        jH                  |      ntG        jJ                  |      }tM        |jE                  t        j                        jO                               D ]Z  \  }!}"||!   }#tQ        |#      }$|r|j                  |#|#      n|#}#| s	||!   |	kD  s7| r|# n
|# d$||!   d%}%|jS                  |"|%|$&       \ nKt        |      r@|D ];  }#tQ        |#      }$|r|j                  |#|#      n|#}#|j?                  ||g|# |$d'(       = t        |      r||   jU                         }&t        |&      rQ|&d!   j%                         d)k  s|&d"   j%                         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	|!   |	kD  s|jW                  |&|!   |	*       % t        |      s4|j                  d   |j                  d   k(  r||   }'nr||g   }'|jY                         }(t        jZ                  |(      j]                  |(ddf      dz   })t        j^                  |'|(d+      }'t        j`                  |'|)k(  d,d-      }'t        jb                  |jd                        jU                         }*t+        t        |'            D ]  }!| s	|!   |	kD  stQ        ||!         }$|'|!   j                  \  }+},|+|k7  s|,|k7  rP|'|!   jE                  t        j                        }-t1        j2                  |-||f      }-|-jE                  tf              }-n|'|!   jE                  tf              }-	 |*|||z   |||z   d
d
f   |-   d.z  t        jh                  |$      d/z  z   |*|||z   |||z   d
d
f   |-<    |jm                  |*       
 |st        jb                  |jd                        S |jd                  jo                  |       |r	 ||       y
y
# tj        $ r Y Sw xY w)0a  
    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 (Optional[List[str]]): List of file paths for each image in the batch.
        fname (str): Output filename for the plotted image grid.
        names (Optional[Dict[int, str]]): Dictionary mapping class indices to class names.
        on_plot (Optional[Callable]): Optional 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): Plotted image grid as a numpy array if save is False, None otherwise.

    Note:
        This function supports both tensor and numpy array inputs. It will automatically
        convert tensor inputs to numpy arrays for processing.
    >   r  r#  r  bboxesr  	batch_idx	keypointsr  rM   rN   r   r:   r  r  r#  Nr  r  r  rk   rJ  r1   c              3   :   K   | ]  }t        |z          y wrN  rV   )rW   rq   nss     rG   rX   zplot_images.<locals>.<genexpr>  s     )F!#a"f+)Fs   g{Gz?   r{   T)re   rf   rh   ri   r9   )r   r}   (   )   r  r  )r   r   rO   rY   g?.).r   ).rN   r    z.1f)r   )@   r  r  r2   )r   r,  g)\(?)r  )r  g      ?g        g?g333333?)8r  r  r   r   r   r  r  getr@   zerosint64r   r  rB   r>   rO  minr  r   fullrO   r  	transposemathr   resizerZ   rd   r   ra   r   r   r   nameastyper   xywhr2xyxyxyxyr  r  r   r   r   r   r  r   arangereshaperepeatwherer   r   r_   rA   r   r   r>  )/r  r  r  r  r  r  r  r  r>  r  r  r  r  r  confsr  r  bs_rR   r   mosaicrI   rq   rU  scalefs	annotatoridxrr  r  r#  is_obbjr   rF   r   r   kpts_image_masksnlindexr   mhmwmaskr  s/                                                 @rG   plot_imagesr    s   F T 0F?:&)..A-q	))!,F1IfQi.q	--/F1I0 **UBHHQbhh7
8C

;"(((KLIZZ"((1BJJ"?@FJJvt$EJJw"(( ;<E::k288ARZZ#@ADZZv&F
6{z&%,,7##%++-||A2A2,,KB1a	R	B	S	B	vvfQiA# WWc"q&k3rAv;2CrxxHF2Y G1R=!3qAF|#41*0)*=*=aA*Fq1q5y!a!e)Q&'G
 rMC1I%EqyIIeai IIeai FE)F1v)F$FG 
a!er\D 	!B	RB&U27^rt]`af]ghI2Y Q(1R=!3qAF|#41Q1q5!a%0$qQNNAE1q5>U1X0C0CCR0HTcNds8a<q.C#hooe,Gd]F6{s%*%6uSzDu:QU|'')S0cAq6k*a/*cAq6k*a/*c2A2g%/f"f"RA-5;**51uAU'RXX(>(E(E(GH EFAs
A"1IE+0		!QaAa:!5*01#1T!WSM6J!++Ce+DE W  aA"1IE+0		!QaANNAq6aSUN_N`a 4yS	(u:V}((*d2eFm6G6G6IT6Qf*f*f"f"s5z* HAa:!5!uQxJGH
 5z99Q<5;;q>1"'*K"'*KBIIbM112q!*=AE"$))K!"DK"$((;%+?c"JKZZ	-224s;/0 !Aa:!5 &wqz 2!,Q!5!5B7bAg#.q>#8#8#BD#&::dQF#;D#';;t#4D#.q>#8#8#>D! "1q1u9a!a%i#: ;D AC G"((SX/\_J_ _ q1q5y!a!e)Q67=!  ##B'cQ(d zz),,''LLe   ) ! !s   Ad''	d43d4dirsegmentposeclassifyc           
         ddl m} ddl}ddlm} | rt        |       j                  n
t        |      }	|r|j                  dddd      \  }
}g d}nZ|r|j                  dd	d
d      \  }
}g d}n;|r|j                  dddd      \  }
}g d}n|j                  dddd      \  }
}g d}|j                         }t        |	j                  d            }t        |      sJ d|	j                          d       |D ]  }	 |j                  |      }|j                  D cg c]  }|j                          }}|j                   dddf   }t#        |      D ]  \  }}|j                   dd|f   j%                  d      }||   j'                  ||d|j(                  dd	       ||   j'                  | ||d      ddd       ||   j+                  ||   d         |d!   j3                          |	d"z  }|
j5                  |d#$       |j7                          |r	 ||       yyc c}w # t,        $ r&}t/        j0                  d| d |        Y d}~Zd}~ww xY w)%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.
        segment (bool, optional): Flag to indicate if the data is for segmentation.
        pose (bool, optional): Flag to indicate if the data is for pose estimation.
        classify (bool, optional): Flag to indicate if the data is for classification.
        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", segment=True)
    r   Ngaussian_filter1drM   )rw   rw   Trh  )rM   r}   rk   rY   ry   )r  rw   )rM   rk   rY   r}   rw   rx   r{   r|   rs   ru   rU   rt   ry   rz   rn   rv   rz   )   rw   )rM   rk   rY   r}   rw   rx   ry   r|   rn   ru   rU   rt   r     rz   r{   rv   rs   r}   )rn   rw   )
rM   rk   rY   r}   rw   rz   r{   r|   rx   ry   zresults*.csvzNo results.csv files found in z, nothing to plot.rO  .)markerr   	linewidth
markersizerk   sigma:smoothr   r  rn   )rq  zPlotting error for z: rN   zresults.pngrb  rc  )rx  ry  rz  scipy.ndimager  r   r  r  r  r   globr>   resolveread_csvrV  stripr  r  r  plotstem	set_titler   r   errorlegendr  r  )r  r  r  r  r  r  r  pdr  r  figr  r  filesr  r   rq   r  rI   r  rU  r:  r  s                          rG   plot_resultsr  O  sC   2 $/$(tDz  d3iH,,q!V$,GR	,,q!W4,HRH	,,q!W4,HRP,,q!W4,HR0	B~./Eu:^78H8H8J7KK]^^: 9	9;;q>D$(LL1q1A1AqD!A!%( 31KK1%,,W51

1a166QST
U1

1/;S\]
^1!r239 qELLN}$EKK3KIIK ! 2  	9LL.qcA3788	9s+    H,H'6B(H,'H,,	I5IIr[  ru  r   
edgecolorsc                    ddl m} t        j                  | ||      \  }}}	t	        t        |             D 
cg c]u  }
|t        t        j                  | |
   |d      dz
  |j                  d   dz
        t        t        j                  ||
   |	d      dz
  |j                  d   dz
        f   w }}
|j                  | |||||       yc c}
w )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   NrZ  T)rw  rN   )rF   ru  r   r  )
rx  ry  r@   histogram2dr  r>   r  digitizer   scatter)vr  r[  ru  r   r  r  rX  xedgesyedgesrI   r   s               rG   plt_color_scatterr    s    " $ >>!QT:D&& s1v
 	 	AaD&594::a=1;LMAaD&594::a=1;LMO	
F  KK1T:KNs   A:Ccsv_filec                    ddl m ddl}ddlm} fd}t        |       } |j                  |       }d}|j                  D cg c]  }|j                          c}|d }|j                  }|dddf   }t        j                  |      }	t        j                  t        |      dz        }
j                  dd	       t!        |      D ]  \  }}|dd||z   f   }||	   }j#                  |
|
|dz          t%        ||d
dd       j'                  ||j)                         dd       j+                  | d|dddi       j-                  dd       ||
z  dk7  sj/                  g          || j1                  d             t3        dt        |      dz         }j                  dd	       j'                  ||ddd       j'                  | ||d      d d!d"#       j+                  d$       j5                  d%       j7                  d&       j9                  d       j;                           || j1                  d'             yc c}w )(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.

    Examples:
        >>> plot_tune_results("path/to/tune_results.csv")
    r   Nr  c                 |    j                  | d       j                          t        j                  d|         y)z#Save one matplotlib plot to 'file'.rb  rc  zSaved N)r  r  r   r  )r  r  s    rG   _save_one_filez)plot_tune_results.<locals>._save_one_file  s.    Dc"		fTFO$rQ   rN   rJ  )r{   r{   Trh  viridisrk  none)ru  r   r  zk+ru   )r  z = z.3gr   rz   )fontdictbothry   )r  	labelsizeztune_scatter_plots.png)r{   rw   ofitness)r  	linestyler   rk   r   r  smoothedrM   r  zFitness vs Iteration	IterationFitnessztune_fitness.png)rx  ry  rz  r  r  r   r  rV  r	  r  r@   argmaxr  r  r>   figurer  subplotr  r
  r   r4  tick_paramsyticks	with_namer  xlabelylabelgridr  )r  r  r  r  r   num_metrics_columnsrq   keysr&  r  r?   rI   r  r  mur  s                  @rG   plot_tune_resultsr7    s    $/% H~H;;x D#||,!AGGI,-@-ABDA1gG
		'A		#d)s"#AJJxdJ3$ 	1a((()qTAq!a% !W9CFSW[[]DR8		QCs2c(#vqk	:Vq1q5A:JJrN	 8%%&>?@ 	aW!"AJJwTJ2HHQvYHGHHQ!'3S
VWHXII$%JJ{JJyHHTNJJL8%%&89:9 -s   I    zruns/detect/expmodule_typestager?   r  c           	         ddl m} dD ]  }||v s y t        | t        j                        r| j
                  \  }}}	}
|	dkD  r|
dkD  r~|d| d|j                  dd      d    d	z  }t        j                  | d   j                         |d
      }t        ||      }|j                  t        j                  |dz        dd      \  }}|j                         }|j                  dd       t        |      D ];  }||   j!                  ||   j#                                ||   j%                  d       = t'        j(                  d| d| d| d       |j+                  |dd       |j-                          t/        j0                  t3        |j5                  d            | d   j                         j7                                yyyy)ag  
    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RTDETRDecoderrN   r:  r  r  r   z_features.pngr   ry   T)rj  g?)wspacehspacert  zSaving z... (/)i,  tight)rd  bbox_inchesz.npy)rx  ry  r   r   r   r   rsplitchunkr  r  r  r  r  r  subplots_adjustr  r  r  r  r   r  r  r  r@   r>  ra   r  r  )rq   r9  r:  r?   r  r  mr  channelsrE  r   r  blocksr  rI   s                  rG   feature_visualizationrN    s    $N  !U\\"%&WW"8VUA:%!)U5';+=+=c1+Eb+I*J-XXA[[1X1=FAx ALL1q5!114LHEArBtD91X "1VAY..011

5!" KK'!E!AhZq9:KKsK8IIKGGCf-.!
0@0@0BC $: #rQ   )zpath/to/results.csvrI  FFFN)   r   rk  r!  )ztune_results.csv)5r  r|  pathlibr   typingr   r   r   r   r   r	   r   r  r@   r   PILr
   r   r   r   r   ultralytics.utilsr   r   r   r   r   r   r   ultralytics.utils.checksr   r   r   ultralytics.utils.filesr   r   r   rd   r  rO  rO   r_   r  r  r  ra   r   ndarrayr  r  r  r7  rN  rb   rQ   rG   <module>rW     s      = = 
   + + * a a a H H 2OG OGd 
}- }-@ "$tBx C  CR h4 4 	4
 
4 4 
4 4n 
 /7bhh7Grzz.Z!%&*"&dcNd%,,

*+d DId 	d
 DcN#d hd d d d d bjjd 
dN %"&@
@	@ @ 	@
 @ h@ @FO# O# O% Ocf OB5; 5;p EGY]^oYp !D# !Dc !Dc !DRV !DrQ   