
    FPh{                     T   d dl Z d dlZd dlZd dlmZ d dlZd dlm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 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Z"e e
jF                  d e
jH                         e
jF                  d e
jJ                         e
jF                  de
jH                        ddddfd       Z& e       d!d       Z'd"dZ(d#dZ)d$dZ*d ed      fd Z+y)%    N)Path)Image	ImageDraw	ImageFont)__version__)LOGGER	TryExceptopsplt_settingsthreaded   )
check_fontcheck_versionis_ascii)increment_pathc                   .    e Zd ZdZd ZddZed        Zy)Colorsa  
    Ultralytics default color palette https://ultralytics.com/.

    This class provides methods to work with the Ultralytics color palette, including converting hex color codes to
    RGB values.

    Attributes:
        palette (list of tuple): List of RGB color values.
        n (int): The number of colors in the palette.
        pose_palette (np.array): A specific color palette array with dtype np.uint8.
    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().)FF3838FF9D97FF701FFFB21DCFD23148F90A92CC173DDB861A933400D4BB2C99A800C2FF3445936473FF0018EC8438FF520085CB38FFFF95C8FF37C7#)      r   )r*      3   )r*      f   )   r0   r   )r*   r,   r*   )r,      r*   )r*   r/   r*   )r*   r-   r*   )r/   r.   r*   )r-   r,   r*   )r*   r,   r,   )r*   r/   r/   )r*   r-   r-   )r,   r*   r,   )r/   r*   r/   )r-   r*   r-   )r   r*   r   )r   r   r*   )r*   r   r   r*   r*   r*   dtypeN)hex2rgbpalettelennnparrayuint8pose_palette)selfhexscs      eC:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\ultralytics/utils/plotting.py__init__zColors.__init__"   s    t7;<t!qW-t<T\\"HHm^_Vcet&5Xgiw&5Wfhw&3[+{\k&m ,.88	5 =s   B+c                 p    | j                   t        |      | j                  z     }|r|d   |d   |d   fS |S )z'Converts hex color codes to RGB values.   r   r   )r6   intr8   )r=   ibgrr?   s       r@   __call__zColors.__call__.   s<    LLQ$&&)%(!adAaD!/a/    c                 ,     t         fddD              S )z@Converts 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)r   rC      NrD   ).0rE   hs     r@   	<genexpr>z!Colors.hex2rgb.<locals>.<genexpr>6   s,     D)QS1q5Q+R0)s   "%)r   rC      )tuple)rN   s   `r@   r5   zColors.hex2rgb3   s     D)DDDrH   N)F)__name__
__module____qualname____doc__rA   rG   staticmethodr5    rH   r@   r   r      s'    

50
 E ErH   r   c                   L    e Zd ZdZddZddZddZddZddZddZ	d	 Z
d
 Zy)	Annotatora7  
    Ultralytics Annotator for train/val mosaics and JPGs and predictions annotations.

    Attributes:
        im (Image.Image or numpy array): The image to annotate.
        pil (bool): Whether to use PIL or cv2 for drawing annotations.
        font (ImageFont.truetype or 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.
    Nc                 |    |j                   j                  sJ d       t        |       }|xs | _        |xs. t	        t        t        |j                        dz  dz        d       _         j                  rt        |t        j                        r|nt        j                  |       _        t        j                   j                         _        	 t!        |rdn|      }|xs8 t	        t        t         j                  j"                        dz  dz        d      }t%        j&                  t)        |      |       _        t1        t2        d      rN fd j*                  _        n9| _        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 _        t<        j>                  g d    _         t<        j>                  g d    _!        y# t,        $ r t%        j.                          _        Y w xY w)zjInitialize the Annotator class with image and line width along with color palette for keypoints and limbs.zQImage not contiguous. Apply np.ascontiguousarray(im) to Annotator() input images.rC   g~jth?zArial.Unicode.ttfgQ?   z9.2.0c                 @    j                   j                  |       dd S )NrC   rP   )fontgetbbox)xr=   s    r@   <lambda>z$Annotator.__init__.<locals>.<lambda>[   s    dii.?.?.B1Q.GrH   r      rK                        	   
      rP      )ri   ri   ri   ri   rg   rg   rg   r   r   r   r   r   rK   rK   rK   rK   rK   rK   rK   )rK   rK   rK   rK   rK   r   r   r   r   r   r   ri   ri   ri   ri   ri   ri   N)"data
contiguousr   pilmaxroundsumshapelw
isinstancer   	fromarrayimr   Drawdrawr   sizer   truetypestrr]   	Exceptionload_defaultr   pil_versiongetsizetfsfskeletoncolorsr<   
limb_color	kpt_color)	r=   rw   
line_width	font_sizer]   ro   example	non_asciirz   s	   `        r@   rA   zAnnotator.__init__J   s   ww!!v#vv! ))	#)HE#bhh-!*;e*C$Da H88&r5;;7bU__R=PDG!tww/DI5!"5M QCc$'',,.?!.Ce.K(Lb$Q%..s4y$?	 ['2$G		!DG$''A+q)DGggkDGbB8b"XBx"bAr7UVXZT[^_ab]cfgijeknoqrmsR1b'Aq6Aq6Aq6Aq6Aq6TUWXSY\]_`[ac !--.no,,-ef  5%224	5s   A/H "H;:H;c           
         t        |t        j                        r|j                         }| j                  st        |      s| j                  j                  || j                  |       |r| j                  j                  |      \  }}|d   |z
  dk\  }| 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t        |d         t        |d         ft        |d         t        |d         f}	}t        j                  | j                  ||	|| j                  t        j                         |rt        j                   |d| j"                  | j$                  	      d   \  }}|d   |z
  dk\  }|d   |z   |r|d   |z
  dz
  n
|d   |z   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                         yy)z%Add one xyxy box to image with label.widthoutliner   r   fillr   r]   rC   ra   	thicknesslineType	fontScaler   N)ru   torchTensortolistro   r   ry   	rectanglert   r]   r   textrD   cv2rw   LINE_AAgetTextSizer   r   putText)
r=   boxlabelcolor	txt_colorwrN   outsidep1p2s
             r@   	box_labelzAnnotator.box_labelg   sI   c5<<(**,C888E?II477EByy((/1a&1*/		##V7SVaZAA
Q#*SVaZA
Q@ $  		AgA
3q6JEXahlhqhqr  #a&k3s1v;/#c!f+s3q6{1KBMM$''2r5DGGckkZua477dggVWXY1Q%!)q.UQY1	Abeai!mKdggr2ub#++FDGG!BqE2a519RUQYQR]#S GG%&*gg%([[2 rH   c                 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 (tensor): Predicted masks on cuda, shape: [n, h, w]
            colors (List[List[Int]]): Colors for predicted masks, [[r, g, b] * n]
            im_gpu (tensor): Image is in cuda, shape: [3, h, w], range: [0, 1]
            alpha (float): Mask transparency: 0.0 fully transparent, 1.0 opaque
            retina_masks (bool): Whether to use high resolution masks or not. Defaults to False.
        r   r   rC   r*   N)devicer4   g     o@ra   dim)dimsr   )ro   r9   asarrayrw   copyr7   permutern   cpunumpyr   tor   tensorfloat32	unsqueezecumprodrp   valuesflipbyter
   scale_imagers   rv   )r=   masksr   im_gpualpharetina_masksmasks_colorinv_alpha_masksmcsim_mask
im_mask_nps              r@   r   zAnnotator.masks   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C<\\^'')//1
#/ZS__ZQUQXQXQ^Q^5_
88NN477# rH   c                 |   | j                   r2t        j                  | j                        j	                         | _        |j
                  \  }}|dk(  xr |dk(  }||z  }t        |      D ]  \  }}	|r&| j                  |   D 
cg c]  }
t        |
       c}
n
t        |      }|	d   |	d   }}||d   z  dk7  sO||d   z  dk7  s[t        |	      dk(  r|	d   }|dk  rtt        j                  | j                  t        |      t        |      f||dt        j                          |ra|j
                  d   }t        | j                        D ]9  \  }}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   }|dk  s|d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                  ||| j                   |   D 
cg c]  }
t        |
       c}
dt        j                  	       < | j                   r| j#                  | j                         y
y
c c}
w c c}
w )aQ  
        Plot keypoints on the image.

        Args:
            kpts (tensor): Predicted keypoints with shape [17, 3]. Each keypoint has (x, y, confidence).
            shape (tuple): Image shape as a tuple (h, w), where h is the height and w is the width.
            radius (int, optional): Radius of the drawn keypoints. Default is 5.
            kpt_line (bool, optional): If True, the function will draw lines connecting keypoints
                                       for human pose. Default is True.

        Note: `kpt_line=True` currently only supports human pose plotting.
        rc   ra   r   r   rC         ?r   )r   r   N)ro   r9   r   rw   r   rs   	enumerater   rD   r   r7   r   circler   r   liner   rv   )r=   kptsrs   radiuskpt_linenkptndimis_poserE   kr_   color_kx_coordy_coordconfskpos1pos2conf1conf2s                       r@   r   zAnnotator.kpts   s    88jj)..0DGZZ
d"**GdODAq=Dt~~a'89'8!s1v'89&QR)G tQqTWGq!Q&7U1X+=+Bq6Q;Q4Dcz 

477S\3w<$@&'SU`c`k`kl $ ::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s{eck 7U1X%*d1ga.@A.EaSTX\]^X_bcXc7U1X%*d1ga.@A.EaSTX\]^X_bcXc$tq?Q.R?Q!s1v?Q.R^_jmjujuv 2 88NN477# 1 :. /Ss   J4J9c                 @    | j                   j                  ||||       y)z"Add rectangle to image (PIL-only).N)ry   r   )r=   xyr   r   r   s        r@   r   zAnnotator.rectangle   s    		Bgu5rH   c           
      (   |dk(  r.| j                   j                  |      \  }}|dxx   d|z
  z  cc<   | j                  r|rY| j                   j                  |      \  }}| j                  j	                  |d   |d   |d   |z   dz   |d   |z   dz   f|       d}d|v rm|j                  d      }| j                   j                  |      \  }	}|D ]8  }
| j                  j                  ||
|| j                          |dxx   |z  cc<   : y| j                  j                  |||| j                          y|rt        j                  |d| j                  | j                        d   \  }}|d   |z
  d	k\  }|d   |z   |r|d   |z
  d	z
  n
|d   |z   d	z   f}t        j                  | j                  |||d
t        j                         d}t        j                  | j                  ||d| j                  || j                  t        j                         y)z'Adds text to an image using PIL or cv2.bottomr   r   r   r2   
r   r   ra   r   r   N)r]   r   ro   ry   r   splitr   r   r   r   r   rw   r   r   )r=   r   r   r   anchor	box_styler   rN   lines_r   r   r   s                r@   r   zAnnotator.text   s   X99$$T*DAqqEQUNE88yy((.1		##RUBqE2a519q="Q%!)a-$PW`#a+	t|

4(yy((.1!DIINN2t)$))NLqEQJE " 		r4idiiHtQ$''TWWUVWX1Q%!)q.UQY1	Abeai!mKdggr2y"ckkJ+	KKr1dggyDGG^a^i^ijrH   c                     t        |t        j                        r|nt        j                  |      | _        t	        j
                  | j                        | _        y)z"Update self.im from a numpy array.N)ru   r   rv   rw   r   rx   ry   )r=   rw   s     r@   rv   zAnnotator.fromarray   s5    "2u{{3"9LNN477+	rH   c                 @    t        j                  | j                        S )z Return annotated image as array.)r9   r   rw   )r=   s    r@   resultzAnnotator.result  s    zz$''""rH   )NNz	Arial.ttfFabc) )r+   r+   r+   r2   )r   F))  r   rl   T)NNr   )r2   topF)rR   rS   rT   rU   rA   r   r   r   r   r   rv   r   rW   rH   r@   rY   rY   <   s4    g:2@"$H.$`6k:,
#rH   rY   rW   r   c           
      4   ddl }ddl}t        j                  dt        d       t        j                  dt
               t        j                  d|dz   d	       t        |j                         d
z         }| dd } |j                  | g d      }|j                  |dddt        d      t        d             t        j                  |dz  d       t        j                          t        j                   dddd      d
   j#                         }	|	d   j%                  |t'        j(                  d||d
z         dz
  d      }
t+        |      D ]=  }|
d   j,                  |   j/                  t1        |      D cg c]  }|dz  	 c}       ? |	d   j3                  d        dt5        |      cxk  rd!k  rXn nU|	d   j7                  t+        t5        |                   |	d   j9                  t;        |j=                               d"d#$       n|	d   j?                  d%       |jA                  d&d'|	d   dd(       |jA                  |d)d*|	d+   dd(       d| ddddf<   tC        jD                  |       d,z  } tG        jH                  t'        jJ                  d-t&        jL                  .      dz        }tO        |dd/ | dd/       D ]5  \  }}tQ        jR                  |      jU                  |d
t1        |      0       7 |	d
   jW                  |       |	d
   jY                  d1       d2D ]*  }d3D ]#  }|	|   jZ                  |   j]                  d4       % , |dz  }t        j                  |d       t        j                          |r	 ||       yyc c}w )5zCPlot training labels including class histograms and box statistics.r   Nignorez&The figure layout has changed to tight)categorymessage)r   zPlotting labels to z
labels.jpgz... r   i@B )r_   yr   height)columnsTautohist2   binsg?)pmax)corner	diag_kindkinddiag_kwsplot_kwszlabels_correlogram.jpg   dpirC   )rh   rh   figsizetight_layoutr   皙?)r   rwidthr*   	instances   Z   rj   )rotationfontsizeclassesr_   r   )r_   r   axr   r   r   r   ra     )r  r  ra   r3   i  r   off)r   r   rC   ra   )r   rightleftr   F)/pandasseabornwarningsfilterwarningsUserWarningFutureWarningr   inforD   rp   	DataFramepairplotdictpltsavefigclosesubplotsravelr   r9   linspacerangepatches	set_colorr   
set_ylabelr7   
set_xticksset_xticklabelslistr   
set_xlabelhistplotr
   	xywh2xyxyr   rv   onesr;   zipr   rx   r   imshowaxisspinesset_visible)boxesclsnamessave_diron_plotpdsnncr_   r  r   rE   imgr   asfnames                    r@   plot_labelsr=    s     H{DlmH}= KK%h&=%>dCD	SWWY]	B(7OE
U$ABA KK$&vRT`djm`nKoKK33=IIK 
aF	>q	A	G	G	IB
1

3R[[BQ7#=c
JA2Y	!Q!!F1I">Iq1s7I">? qE[!3u:
1s5z*+
1d5<<>2R"M
1#KKSCBqEK=KKWRU#KF E!QqS&MMM% 4'E
//"''/BSH
ICDS	5#;/Ss%%cF3K%H 0qELLqEJJu3AqELLO''. 4  |#EKK3IIK 5 #?s   =N
zim.jpggRQ?rj   FTc                 >   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                         |t        | d         t        | d         t        | d	         t        | d
         dd|rdndf   }	|ro|j                  j                  dd       t!        t#        |      j%                  d            }
t'        j(                  |	ddddf         j+                  |
dd       |	S )a  
    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 or list): A tensor or list representing the bounding box in xyxy format.
        im (numpy.ndarray): The input image.
        file (Path, optional): The path where the cropped image will be saved. Defaults to 'im.jpg'.
        gain (float, optional): A multiplicative factor to increase the size of the bounding box. Defaults to 1.02.
        pad (int, optional): The number of pixels to add to the width and height of the bounding box. Defaults to 10.
        square (bool, optional): If True, the bounding box will be transformed into a square. Defaults to False.
        BGR (bool, optional): If True, the image will be saved in BGR format, otherwise in RGB. Defaults to False.
        save (bool, optional): If True, the cropped image will be saved to disk. Defaults to True.

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

    Example:
        ```python
        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   rP   NrC   r   r   )r   r   )r   ra   )r   r   )r   rC   T)parentsexist_okz.jpg._   )qualitysubsampling)ru   r   r   stackr
   	xyxy2xywhviewrp   r   r*  long
clip_boxesrs   rD   parentmkdirr|   r   with_suffixr   rv   save)xyxyrw   filegainpadsquareBGRrL  bcropfs              r@   save_one_boxrV  >  sc   > dELL){{4 diiA&'AQU8<<?1%//2!QR%ABx$$AaeH==  "DNN4"c$t*oc$t*o-s4:s4:/NPdX[STacPddeD$6t$0089S$B$Y(--a-KKrH   r3   )r   r-   z
images.jpgc
           	        ) t        | t        j                        r,| j                         j	                         j                         } t        |t        j                        r|j                         j                         }t        |t        j                        r|j                         j                         }t        |t        j                        r1|j                         j                         j                  t              }t        |t        j                        r|j                         j                         }t        |t        j                        r|j                         j                         }d}
d}| 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 ]U  \  }}||k(  r nKt        ||)z  z        t        ||)z  z        }}|j!                  dd	d      }|||||z   |||z   d
d
f<   W |
)z  t        ||      z  }|dk  rZt#        j                  ||z        }t#        j                  ||z        }t%        j&                  |t)        )fd||fD                    }t        ||z   )z  dz        }t+        |t-        |dz        |d|      }t/        dz         D ]	  }t        ||)z  z        t        ||)z  z        }}|j1                  ||||z   ||z   gd
dd	       |r5|j3                  |dz   |dz   ft5        ||         j6                  d
d d       t9        |      dkD  s||k(  }||   j                  d      }t9        |      r-t;        j<                  ||d
df         j>                  }|j                  d   dk(  }|rd
n||df   }|j                  d   r<|j                         dk  r|dd	gxx   |z  cc<   |ddgxx   |z  cc<   n
|dk  r||z  }|dd	gxx   |z  cc<   |ddgxx   |z  cc<   t        |j>                  jA                               D ]Z  \  }}||   }tC        |      } |r|jE                  ||      n|}|s	||   dkD  s7|r| n
| d||   d}!|jG                  ||!|        \ nKt9        |      r@|D ];  }tC        |      } |r|jE                  ||      n|}|j3                  ||f| | d       = t9        |      r||   jI                         }"t9        |"      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/        t9        |"            D ]!  }s	|   dkD  s|jK                  |"|          # t9        |      s|j                  d   |j                  d   k(  r||   }#nr||g   }#|jM                         }$t        jN                  |$      jQ                  |$ddf      dz   }%t        jR                  |#|$d       }#t        jT                  |#|%k(  d!d"      }#t        jV                  |jX                        jI                         }t        j>                  jA                               D ]  \  }}s	|   dkD  stC        ||         } |#|   j                  \  }&}'|&|k7  s|'|k7  rP|#|   j                  t        j                        }(t%        j&                  |(||f      }(|(j                  tZ              }(n|#|   j                  tZ              }(t]        j^                  t`              5  ||||z   |||z   d
d
f   |(   d#z  t        jb                  |       d$z  z   ||||z   |||z   d
d
f   |(<   d
d
d
        |je                  |        |jX                  jg                  |       |	r	 |	|       y
y
# 1 sw Y   VxY w)%zPlot image grid with labels.i  rK   r   r   r   r*   ra   r3   rC   Nc              3   :   K   | ]  }t        |z          y w)NrL   )rM   r_   nss     r@   rO   zplot_images.<locals>.<genexpr>  s     )Fv!#a"f+vs   g{Gz?rj   T)r   r   ro   r   r2   )r   rl   (   )   r[  r[  )r   r   rD   rP   g)\(?g      ? z.1f)r   )r   r   ).r   ).r   )r.  g      ?g        g?g333333?)4ru   r   r   r   floatr   astyperD   rs   minr9   ceilrp   fullr;   r   	transposemathr   resizerQ   rY   rq   r!  r   r   r   namer7   r
   r*  Tr   r   getr   r   r   rr   arangereshaperepeatwherer   rw   bool
contextlibsuppressr}   r:   rv   rL  )*images	batch_idxr2  bboxesr   r   pathsr<  r3  r5  max_sizemax_subplotsbsr   rN   r   mosaicrE   rw   r_   r   scalefs	annotatoridxr  r1  labelsr   jr   r?   r   r   kpts_image_masksnlindexmhmwmaskrY  s*                                            @r@   plot_imagesr  n  sz    &%,,'##%++-#u||$ggioo&%,,'##%%&		!!#**3/$%xxz!)U\\*MMO))+	HL,,KB1a	R	B	s	B	vvfQiA# WWc"q&k3rAv;2CrxxHF6"21R=!3qAF|#41\\!Q"&(qQw!a%"# # rMC1I%EqyIIeai IIeai FE)F1v)F$FG 
a!er\D 	!B&U27^rt]bcI1q5\1R=!3qAF|#41Q1q5!a%0$qQNNAE1q5>U1X0C0CCR0HTcNds8a<q.C#hooe,G6{fS"1"Wo688aA-%t6#q&>;;q>yy{d*q!f*q!f*q!f"q!f"'(89FAs
A"1IE+0		!QaAa4*01#1T!WSM6J!++Ce+D : W A"1IE+0		!QaANNAq6aSUdNS ! 4yS	(u:V}((*d2eFm6G6G6IT6Qf*f*f"f"s5z*Aa4!uQx0 +
 5z99Q<5;;q>1"'*K"'*KBIIbM112q!*=AE"$))K!"DK"$((;%+?c"JKZZ	-224'(89FAsa4 &wqz 2!,Q!5!5B7bAg#.q>#8#8#BD#&::dQF#;D#';;t#4D#.q>#8#8#>D'00;<>qQw!a%QR?R<STX<Y\_<_bdbjbjkpbqtwbw<wBqQw!a%23D9 <; : ##B'U V LLe 	 <;s   A	aac           
         ddl }ddlm} | rt        |       j                  n
t        |      }|r!t        j                  dddd      \  }	}
g d}nf|r!t        j                  dd	d
d      \  }	}
g d}nC|r!t        j                  dddd      \  }	}
g d}n t        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!   j1                          |d"z  }|	j3                  |d#$       t        j4                          |r	 ||       yyc c}w # t*        $ r&}t-        j.                  d| d |        Y d}~^d}~ww xY w)%aR  
    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. Defaults to 'path/to/results.csv'.
        dir (str, optional): Directory where the CSV file is located if 'file' is not provided. Defaults to ''.
        segment (bool, optional): Flag to indicate if the data is for segmentation. Defaults to False.
        pose (bool, optional): Flag to indicate if the data is for pose estimation. Defaults to False.
        classify (bool, optional): Flag to indicate if the data is for classification. Defaults to False.
        on_plot (callable, optional): Callback function to be executed after plotting. Takes filename as an argument.
            Defaults to None.

    Example:
        ```python
        from ultralytics.utils.plotting import plot_results

        plot_results('path/to/results.csv', segment=True)
        ```
    r   Ngaussian_filter1drC   )rf   rf   Tr  )r   rP   rC   ra   rh   )   rf   )r   rC   ra   rP   rl   rf   ri   rj   re   rb   rd   rK   rg   rh   rk   r[   ri   )   rf   )r   rC   ra   rP   rl   rf   rg   rj   rk   rb   rd   rK   rc   r  rh   ri   r[   re   rl   )r[   rf   )
r   rC   ra   rP   rl   rh   ri   rj   rf   rg   zresults*.csvzNo results.csv files found in z, nothing to plot.r]  .)markerr   	linewidth
markersizera   sigma:smoothr   r  r[   )r
  zWARNING: Plotting error for z: r   zresults.pngr   r   )r  scipy.ndimager  r   rI  r  r  r  r'  globr7   resolveread_csvr   stripr   r   r^  plotstem	set_titler}   r   warninglegendr  r  )rN  dirsegmentposeclassifyr5  r6  r  r4  figr  r  filesrU  rm   r_   r;  rE   r|  r   er<  s                         r@   plot_resultsr    s2   , /$(tDz  d3iH,,q!V$GR	,,q!W4HRG	,,q!W4HRO,,q!W4HR/	B~./Eu:^78H8H8J7KK]^^:	D;;q>D$(LL1LqLA1AqD!A!%(1KK1%,,W51

1a166QST
U1

1/;S\]
^1!r2 )  qELLN}$EKK3KIIK ! 2  	DNN9!BqcBCC	Ds+   
H:)H5 B(H:5H::	I)I$$I)c                    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 }
}	t        j                  | ||
|||       yc c}	w )a{  
    Plots 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. Defaults to 20.
        cmap (str, optional): Colormap for the scatter plot. Defaults to 'viridis'.
        alpha (float, optional): Alpha for the scatter plot. Defaults to 0.8.
        edgecolors (str, optional): Edge colors for the scatter plot. Defaults to 'none'.

    Examples:
        >>> v = np.random.rand(100)
        >>> f = np.random.rand(100)
        >>> plt_color_scatter(v, f)
    r   T)r  r   r   )r?   cmapr   
edgecolorsN)	r9   histogram2dr!  r7   r_  digitizers   r  scatter)vrU  r   r  r   r  r   xedgesyedgesrE   r   s              r@   plt_color_scatterr  1  s    & >>!QT:D&& Z__bcd_eYfhYfTU 	SQqT66:DJJqMA<MNQqT66:DJJqMA<MNO 	PYf  h
 KK1T:Nhs   A:Cc                     ddl }ddlm} t        |       } |j	                  |       }d}|j
                  D cg c]  }|j                          c}|d }|j                  }|dddf   }t        j                  |      }t        j                  t        |      dz        }	t        j                  dd       t        |      D ]  \  }
}|dd|
|z   f   }||   }t        j                   |	|	|
dz          t#        ||d	d
d       t        j$                  ||j'                         dd       t        j(                  | d|dddi       t        j*                  dd       |
|	z  dk7  st        j,                  g         | j/                  d      }t        j0                  |d       t        j2                          t5        j6                  d|        t9        dt        |      dz         }t        j                  dd       t        j$                  ||ddd       t        j$                  | ||d !      d"d#d$%       t        j(                  d&       t        j:                  d'       t        j<                  d(       t        j>                  d       t        j@                          | j/                  d)      }t        j0                  |d       t        j2                          t5        j6                  d|        yc c}w )*a  
    Plot the evolution results stored in an '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. Defaults to 'tune_results.csv'.

    Examples:
        >>> plot_tune_results('path/to/tune_results.csv')
    r   Nr  r   r   )rj   rj   Tr  viridisr  none)r  r   r  zk+rd   )r  z = z.3grz   ri   )fontdictbothrh   )r.  	labelsizeztune_scatter_plots.pngr   r   zSaved )rj   rf   ofitness)r  	linestyler   ra   r  r  smoothedrC   r  zFitness vs Iteration	IterationFitnessztune_fitness.png)!r  r  r  r   r  r   r  r   r9   argmaxrc  r`  r7   r  figurer   subplotr  r  rp   titletick_paramsyticks	with_namer  r  r   r  r!  xlabelylabelgridr  )csv_filer6  r  rm   num_metrics_columnsr_   keysr  r|  r8   rE   r   r  murN  s                  r@   plot_tune_resultsr  M  sS    / H~H;;x D#||,|!AGGI|,-@-ABDA1gG
		'A		#d)s"#AJJxd3$1a((()qTAq!a% !W9B6RW[[]DR8		QCs2c(#vqk:Vq1q5A:JJrN   67DKK#IIK
KK&  	aW!"AJJwT2HHQvYGHHQ!'3S
VWXII$%JJ{JJyHHTNJJL01DKK#IIK
KK& I -s   K;c           
         g }t        |       D ]  \  }}|d|ddf   j                         j                  dd      \  }}}t        j                  |j
                  d   df|      }|j                  t        j                  ||t        j                  |      |fd              t        j                  |d      j                         }|dddf   |dddf   |ddddf   fS )zZConvert model output to target format [batch_id, class_id, x, y, w, h, conf] for plotting.Nrf   )rP   r   r   r   r   rC   )r   r   r   r   ra  rs   appendcatr
   rE  r   )	outputmax_dettargetsrE   r  r   r   r2  r|  s	            r@   output_to_targetr    s    G&!18G8RaR<,,.44YBT3JJ

1q)1-uyy!S#--*<d!CQGH " ii#))+G1a4='!Q$-AB77rH       zruns/detect/expc           	      t   dD ]  }||v s y | j                   \  }}}}	|dkD  r|	dkD  r|d| d|j                  d      d    dz  }
t        j                  | d	   j	                         |d	
      }t        ||      }t        j                  t        j                  |dz        dd      \  }}|j                         }t        j                  dd       t        |      D ];  }||   j                  ||   j                                ||   j                  d       = t!        j"                  d|
 d| d| d       t        j$                  |
dd       t        j&                          t)        j*                  t-        |
j/                  d            | d	   j	                         j1                                yyy)a  
    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. Defaults to 32.
        save_dir (Path, optional): Directory to save results. Defaults to Path('runs/detect/exp').
    )DetectPoseSegmentNr   stager   r  r   z_features.pngr   r   rh   T)r  g?)wspacehspacer  zSaving z... (/),  tight)r   bbox_inchesz.npy)rs   r   r   chunkr   r_  r  r  rc  r`  r  subplots_adjustr!  r-  squeezer.  r   r  r  r  r9   rL  r|   rK  r   )r_   module_typer  r8   r4  mbatchchannelsr   r   rU  blocksr  r  rE   s                  r@   feature_visualizationr    sw    + + &'WW"E8VUzeaiugQ{'8'8'=b'A&B-PPQqTXXZq98,,tyyQ/FRXXZ45qAqELL**,-qEJJu  	gaSaS(156A3G4		
AMM&)*AaDHHJ,<,<,>?  zrH   )zpath/to/results.csvr   FFFN)   r  r  r  )ztune_results.csv)r  ),rm  rc  r  pathlibr   r   matplotlib.pyplotpyplotr  r   r9   r   PILr   r   r   r   r   ultralytics.utilsr   r	   r
   r   r   checksr   r   r   r  r   r   r   rY   r=  rV  zerosr   r;   r  r  r  r  r  r  rW   rH   r@   <module>r     s=       
    + + * L L 7 7 !!E !EH 
G# G#T "$tBx 3  3l !%XTr%UZae -` 
  rxx4bhhq1RXXgRZZ8"@ 
@F ; ;|O87!t8 46EV@W @rH   