
    FPh                        d dl Z d dlmZ d dlmZmZmZmZ d dlZ	d dl
Z
	 d$de
j                  dee   dee   dede
j                  f
d	Zd
edeee   ddf   fdZde
j                  dedede
j                  fdZdede	j"                  fdZdedededee	j"                     fdZdeedf   dededeeee      ee   f   fdZde
j                  dee   de
j                  fdZde
j                  dee   de
j                  fdZde
j                  dee   dedede
j                  f
dZde	j"                  d ed!edee	j"                  ef   fd"Zde
j                  de
j                  fd#Zy)%    N)product)Any	GeneratorListTupleboxescrop_boxorig_boxatolreturnc                    t        j                  |t         j                  | j                        }t        j                  |t         j                  | j                        }t	        | |      j                         } t        j
                  | |dddf   |d      }t        j
                  | |dddf   |d      }t        j                  ||       }t        j                  |d      S )zCReturn a boolean tensor indicating if boxes are near the crop edge.)dtypedeviceNr   )r   rtol   dim)torch	as_tensorfloatr   uncrop_boxes_xyxyiscloselogical_andany)r   r	   r
   r   crop_box_torchorig_box_torchnear_crop_edgenear_image_edges           eC:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\ultralytics/models/sam/amg.pyis_box_near_crop_edger       s    
 __XU[[VN__XU[[VNeX.446E]]5.q*ASTUNmmE>$'+BTUVO&&~7GHN99^++    
batch_sizec              '     K   rt        fdD              sJ d       t        d         | z  t        t        d         | z  dk7        z   }t        |      D ]   }D cg c]  }||| z  |dz   | z    c} " yc c}w w)z/Yield batches of data from the input arguments.c              3   R   K   | ]  }t        |      t        d          k(     yw)r   N)len).0aargss     r   	<genexpr>z!batch_iterator.<locals>.<genexpr>   s#     =1A#d1g,.s   $'z-Batched iteration must have same-size inputs.r   r   N)allr%   intrange)r"   r(   	n_batchesbargs    `   r   batch_iteratorr0      s     C===n?nn=DG
*ST!W
1Ja1O-PPI9CGH4Cs1z>1q5J"674HH Hs   AB"A?7Bmasksmask_thresholdthreshold_offsetc                 $   | ||z   kD  j                  dt        j                        j                  dt        j                        }| ||z
  kD  j                  dt        j                        j                  dt        j                        }||z  S )z
    Computes the stability score for a batch of masks.

    The stability score is the IoU between the binary masks obtained by thresholding the predicted mask logits at high
    and low values.
    )r   )sumr   int16int32)r1   r2   r3   intersectionsunionss        r   calculate_stability_scorer;   !   s     ~0@@AFFrQVQ\Q\F]aabdhmhshs b uM)99:??%++?VZZ[]ejepepZqF6!!r!   
n_per_sidec                    dd| z  z  }t        j                  |d|z
  |       }t        j                  |dddf   | df      }t        j                  |dddf   d| f      }t        j                  ||gd      j	                  dd      S )zDGenerate a 2D grid of evenly spaced points in the range [0,1]x[0,1].r      Nr5   )axis)nplinspacetilestackreshape)r<   offsetpoints_one_sidepoints_xpoints_ys        r   build_point_gridrI   0   s    !j.!Fkk&!f*jAOwwtQw/*aAHwwq$w/!ZAH88Xx(r2::2qAAr!   n_layersscale_per_layerc           
      t    t        |dz         D cg c]  }t        t        | ||z  z               c}S c c}w )z)Generate point grids for all crop layers.r   )r,   rI   r+   )r<   rJ   rK   is       r   build_all_layer_point_gridsrN   9   s=    PUV^abVbPcdPc1S!/C!DEFPcddds   !5im_size.overlap_ratioc           	      h   g g }}| \  }}t        ||      }|j                  dd||g       |j                  d       d }t        |      D ]  }	d|	dz   z  }
t        ||z  d|
z  z        } |||
|      } |||
|      }t        |
      D cg c]  }t        ||z
  |z         }}t        |
      D cg c]  }t        ||z
  |z         }}t	        ||      D ]J  \  }}||t        ||z   |      t        ||z   |      g}|j                  |       |j                  |	dz          L  ||fS c c}w c c}w )zs
    Generates a list of crop boxes of different sizes.

    Each layer has (2**i)**2 boxes for the ith layer.
    r   c                 V    t        t        j                  ||dz
  z  | z   |z              S )z4Crops bounding boxes to the size of the input image.r   )r+   mathceil)orig_lenn_cropsoverlaps      r   crop_lenz%generate_crop_boxes.<locals>.crop_lenM   s)    499g15@GKLMMr!   r>   r   )minappendr,   r+   r   )rO   rJ   rP   
crop_boxes
layer_idxsim_him_w
short_siderX   i_layern_crops_per_siderW   crop_wcrop_hrM   crop_box_x0crop_box_y0x0y0boxs                       r   generate_crop_boxesri   >   sl     
JJD$T4J q!T4()aN ?1-mj0A8H4HIJ$ 0':$ 0':<ABR<ST<SqsFW,12<ST<ABR<ST<SqsFW,12<ST k;7FBr3rF{D13rF{D3IJCc"gk* 8 #  z!! UTs   
D*1D/c                     |\  }}}}t        j                  ||||gg| j                        }t        | j                        dk(  r|j                  d      }| |z   S )z4Uncrop bounding boxes by adding the crop box offset.r      r   r   tensorr   r%   shape	unsqueeze)r   r	   rf   rg   _rE   s         r   r   r   d   sZ    LBAq\\BB+,U\\BF
5;;1!!!$6>r!   pointsc                     |\  }}}}t        j                  ||gg| j                        }t        | j                        dk(  r|j                  d      }| |z   S )z,Uncrop points by adding the crop box offset.rk   rl   r   rm   )rr   r	   rf   rg   rq   rE   s         r   uncrop_pointsrt   n   sT    LBAq\\B8*V]];F
6<<A!!!$F?r!   orig_horig_wc                     |\  }}}}|dk(  r|dk(  r||k(  r||k(  r| S |||z
  z
  |||z
  z
  }	}|||z
  ||	|z
  f}
t         j                  j                  j                  | |
d      S )z8Uncrop masks by padding them to the original image size.r   )value)r   nn
functionalpad)r1   r	   ru   rv   rf   rg   x1y1pad_xpad_yr{   s              r   uncrop_masksr   x   s    NBB	Qw27rV|fR"W%vb'95Eurz2urz
*C88""5#Q"77r!   maskarea_threshmodec                    ddl }|dv sJ |dk(  }|| z  j                  t        j                        }|j	                  |d      \  }}}}	|dddf   dd }
t        |
      D cg c]  \  }}||k  s|dz    }}}|s| dfS dg|z   }|sBt        |      D cg c]	  }||vs| c}xs" t        t        j                  |
            dz   g}t        j                  ||      } | d	fS c c}}w c c}w )
zfRemove small disconnected regions or holes in a mask, returning the mask and a modification indicator.r   N>   holesislandsr      r5   r   FT)
cv2astyper@   uint8connectedComponentsWithStats	enumerater,   r+   argmaxisin)r   r   r   r   correct_holesworking_maskn_labelsregionsstatsrq   sizesrM   ssmall_regionsfill_labelss                  r   remove_small_regionsr      s   ''''GOM!D(00:L"%"B"B<QR"SHgua!R%LE'0'7K'7tq!1{?QU'7MKU{#%K"'/J/QQk5Iq/JisSUS\S\]bScOdghOhNi777K(D: L Ks   #C%1C%	C+ C+c                    t        j                  |       dk(  r1t        j                  g | j                  dd dd| j                  iS | j                  }|dd \  }}t        |      dkD  r| j                  dd      n| j                  d      } t        j                  | d	      \  }}|t        j                  ||j                  
      dddf   z  }t        j                  |d	      \  }}||| z  z   }t        j                  |d	      \  }}t        j                  | d	      \  }	}|	t        j                  ||	j                  
      dddf   z  }
t        j                  |
d	      \  }}|
||	 z  z   }
t        j                  |
d	      \  }}||k  ||k  z  }t        j                  ||||gd	      }|| j                  d      z  }t        |      dkD  r |j                  g |dd d S |d   S )z
    Calculates boxes in XYXY format around masks.

    Return [0,0,0,0] for an empty mask. For input shape C1xC2x...xHxW, the output shape is C1xC2x...x4.
    r   N   r   r>   r5   r   rk   )r   numelzerosro   r   r%   flattenrp   maxarangerY   rC   rD   )r1   ro   hw	in_heightrq   in_height_coordsbottom_edges	top_edgesin_widthin_width_coordsright_edges
left_edgesempty_filterouts                  r   batched_mask_to_boxr      s    {{5Q{{EEKK,EaEEE KKE:DAq$'JNEMM!R 8JE99U+LIq 5<<):J:J#KDRSG#TTii 0b9OL!'!	z*::99-26LIq ))Er*KHaa!Hq!QQOYYB7NK%hY7OIIo26MJ  *,	1IJL
++z9k<Hb
QC
,))"-
-C +.e*q.;3;;&cr
&A&Dc!fDr!   )g      4@)rS   	itertoolsr   typingr   r   r   r   numpyr@   r   Tensorr+   r   r    r0   r;   ndarrayrI   rN   ri   r   rt   r   strboolr   r    r!   r   <module>r      s     . .   )-, ,$(I,$(I, !&, 27,Is IiS	48M.N I"U\\ "5 "\a "fkfrfr "B B BeC e3 eQT eY]^`^h^hYi e
#"sCx #"C #"',#"16tDIS	7Q1R#"LU\\ T#Y 5<< %,, $s)  8 8S	 83 8PS 8X]XdXd 8rzz  S USUS]S]_cScMd (#Eu|| #E #Er!   