Ë
    Fêñiè5  ã                  óH   — d dl mZ d dlZd dlZd dlZd dlmZ  G d„ d«      Zy)é    )ÚannotationsN)ÚLOGGERc                  óR   ‡ — e Zd ZdZdd	ˆ fd„Zd
dd„Zdd„Zd
dd„Zdd„Zdd„Z	ˆ xZ
S )ÚGMCa  Generalized Motion Compensation (GMC) class for tracking and object detection in video frames.

    This class provides methods for tracking and detecting objects based on several tracking algorithms including ORB,
    SIFT, ECC, and Sparse Optical Flow. It also supports downscaling of frames for computational efficiency.

    Attributes:
        method (str | None): The tracking method to use. Options include 'orb', 'sift', 'ecc', 'sparseOptFlow', None.
        downscale (int): Factor by which to downscale the frames for processing.
        prevFrame (np.ndarray | None): Previous frame for tracking.
        prevKeyPoints (tuple | np.ndarray | None): Keypoints from the previous frame.
        prevDescriptors (np.ndarray | None): Descriptors from the previous frame.
        initializedFirstFrame (bool): Flag indicating if the first frame has been processed.

    Methods:
        apply: Apply the chosen method to a raw frame and optionally use provided detections.
        apply_ecc: Apply the ECC algorithm to a raw frame.
        apply_features: Apply feature-based methods like ORB or SIFT to a raw frame.
        apply_sparseoptflow: Apply the Sparse Optical Flow method to a raw frame.
        reset_params: Reset the internal parameters of the GMC object.

    Examples:
        Create a GMC object and apply it to a frame
        >>> gmc = GMC(method="sparseOptFlow", downscale=2)
        >>> frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
        >>> warp = gmc.apply(frame)
        >>> print(warp.shape)
        (2, 3)
    c                ó~  •— t         ‰| �  «        || _        t        d|«      | _        | j                  dk(  r]t        j                  d«      | _        t        j                  «       | _	        t        j                  t
        j                  «      | _        �n| j                  dk(  rct        j                  ddd¬«      | _        t        j                  ddd¬«      | _	        t        j                  t
        j                  «      | _        nœ| j                  dk(  rCd	}d
}t
        j                  | _        t
        j"                  t
        j$                  z  ||f| _        nJ| j                  dk(  rt)        dddddd¬«      | _        n$| j                  dv rd| _        nt-        d|› �«      ‚d| _        d| _        d| _        d| _        y)a6  Initialize a Generalized Motion Compensation (GMC) object with tracking method and downscale factor.

        Args:
            method (str): The tracking method to use. Options include 'orb', 'sift', 'ecc', 'sparseOptFlow', 'none'.
            downscale (int): Downscale factor for processing frames.
        é   Úorbé   Úsifté   ç{®Gáz”?)ÚnOctaveLayersÚcontrastThresholdÚedgeThresholdÚecciˆ  g�íµ ÷Æ°>ÚsparseOptFlowiè  g{®Gáz„?Fg{®Gáz¤?)Ú
maxCornersÚqualityLevelÚminDistanceÚ	blockSizeÚuseHarrisDetectorÚk>   NÚNoneÚnoneNzUnknown GMC method: )ÚsuperÚ__init__ÚmethodÚmaxÚ	downscaleÚcv2ÚFastFeatureDetector_createÚdetectorÚ
ORB_createÚ	extractorÚ	BFMatcherÚNORM_HAMMINGÚmatcherÚSIFT_createÚNORM_L2ÚMOTION_EUCLIDEANÚ	warp_modeÚTERM_CRITERIA_EPSÚTERM_CRITERIA_COUNTÚcriteriaÚdictÚfeature_paramsÚ
ValueErrorÚ	prevFrameÚprevKeyPointsÚprevDescriptorsÚinitializedFirstFrame)Úselfr   r   Únumber_of_iterationsÚtermination_epsÚ	__class__s        €ú`/var/www/pod-logistic/pod-ai/venv/lib/python3.12/site-packages/ultralytics/trackers/utils/gmc.pyr   zGMC.__init__+   sg  ø€ ô 	‰ÑÔàˆŒÜ˜Q 	Ó*ˆŒà�;‰;˜%ÒÜ×:Ñ:¸2Ó>ˆDŒMÜ Ÿ^™^Ó-ˆDŒNÜŸ=™=¬×)9Ñ)9Ó:ˆDŽLà�[‰[˜FÒ"ÜŸO™O¸!ÈtÐceÔfˆDŒMÜ Ÿ_™_¸1ÐPTÐdfÔgˆDŒNÜŸ=™=¬¯©Ó5ˆD�Là�[‰[˜EÒ!Ø#'Ð Ø"ˆOÜ ×1Ñ1ˆDŒNÜ ×2Ñ2´S×5LÑ5LÑLÐNbÐdsÐtˆD�Mà�[‰[˜OÒ+Ü"&Ø¨dÀÈQÐbgÐkoô#ˆDÕð �[‰[Ð2Ñ2ØˆD�KäÐ3°F°8Ð<Ó=Ð=àˆŒØ!ˆÔØ#ˆÔØ%*ˆÕ"ó    c                óî   — | j                   dv r| j                  ||«      S | j                   dk(  r| j                  |«      S | j                   dk(  r| j                  |«      S t	        j
                  dd«      S )uU  Estimate a 2Ã—3 motion compensation warp for a frame.

        Args:
            raw_frame (np.ndarray): The raw frame to be processed, with shape (H, W, C).
            detections (list, optional): List of detections to be used in the processing.

        Returns:
            (np.ndarray): Transformation matrix with shape (2, 3).

        Examples:
            >>> gmc = GMC(method="sparseOptFlow")
            >>> raw_frame = np.random.rand(480, 640, 3)
            >>> transformation_matrix = gmc.apply(raw_frame)
            >>> print(transformation_matrix.shape)
            (2, 3)
        >   r	   r   r   r   é   r   )r   Úapply_featuresÚ	apply_eccÚapply_sparseoptflowÚnpÚeye)r6   Ú	raw_frameÚ
detectionss      r:   Úapplyz	GMC.applyV   sk   € ð" �;‰;˜/Ñ)Ø×&Ñ& y°*Ó=Ð=Ø�[‰[˜EÒ!Ø—>‘> )Ó,Ð,Ø�[‰[˜OÒ+Ø×+Ñ+¨IÓ6Ð6ä—6‘6˜!˜Q“<Ðr;   c           	     ó¤  — |j                   \  }}}|dk(  r$t        j                  |t        j                  «      n|}t	        j
                  ddt        j                  ¬«      }| j                  dkD  rIt        j                  |dd«      }t        j                  ||| j                  z  || j                  z  f«      }| j                  s|j                  «       | _        d| _
        |S 	 t        j                  | j                  ||| j                  | j                  dd	«      \  }}|S # t         $ r#}t#        j$                  d
|› �«       Y d}~|S d}~ww xY w)a*  Apply the ECC (Enhanced Correlation Coefficient) algorithm to a raw frame for motion compensation.

        Args:
            raw_frame (np.ndarray): The raw frame to be processed, with shape (H, W, C).

        Returns:
            (np.ndarray): Transformation matrix with shape (2, 3).

        Examples:
            >>> gmc = GMC(method="ecc")
            >>> processed_frame = gmc.apply_ecc(np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]))
            >>> print(processed_frame)
            [[1. 0. 0.]
             [0. 1. 0.]]
        r   r=   )Údtypeç      ð?)r   r   g      ø?TNr   z.findTransformECC failed; using identity warp. )Úshaper    ÚcvtColorÚCOLOR_BGR2GRAYrA   rB   Úfloat32r   ÚGaussianBlurÚresizer5   Úcopyr2   ÚfindTransformECCr+   r.   Ú	Exceptionr   Úwarning)	r6   rC   ÚheightÚwidthÚcÚframeÚHÚ_Úes	            r:   r?   zGMC.apply_eccp   s$  € ð  %Ÿ?™?Ñˆ��qØ?@ÀAºv”—‘˜Y¬×(:Ñ(:Ô;È9ˆÜ�F‰F�1�aœrŸz™zÔ*ˆð �>‰>˜CÒÜ×$Ñ$ U¨F°CÓ8ˆEÜ—J‘J˜u u°·±Ñ'>ÀÈ$Ï.É.Ñ@XÐ&YÓZˆEð ×)Ò)Ø"ŸZ™Z›\ˆDŒNØ)-ˆDÔ&ØˆHð	QÜ×)Ñ)¨$¯.©.¸%ÀÀDÇNÁNÐTX×TaÑTaÐcgÐijÓk‰FˆQ�ð ˆøô ò 	QÜ�N‰NÐKÈAÈ3ÐO×PÐPàˆûð	Qús   Ã%<D# Ä#	EÄ,E
Å
Ec                óx
  — |j                   \  }}}|dk(  r$t        j                  |t        j                  «      n|}t	        j
                  dd«      }| j                  dkD  rPt        j                  ||| j                  z  || j                  z  f«      }|| j                  z  }|| j                  z  }t	        j                  |«      }d|t        d|z  «      t        d|z  «      …t        d|z  «      t        d|z  «      …f<   |�M|D ]H  }	|	dd | j                  z  j                  t        j                  «      }
d	||
d
   |
d   …|
d	   |
d   …f<   ŒJ | j                  j                  ||«      }| j                  j                  ||«      \  }}| j                   sR|j#                  «       | _        t#        j"                  |«      | _        t#        j"                  |«      | _        d| _        |S | j*                  j-                  | j(                  |d«      }g }g }dt	        j.                  ||g«      z  }t1        |«      d	k(  rK|j#                  «       | _        t#        j"                  |«      | _        t#        j"                  |«      | _        |S |D ]Ô  \  }}|j2                  d|j2                  z  k  sŒ#| j&                  |j4                     j6                  }||j8                     j6                  }|d	   |d	   z
  |d
   |d
   z
  f}t	        j:                  |d	   «      |d	   k  sŒ”t	        j:                  |d
   «      |d
   k  sŒ³|j=                  |«       |j=                  |«       ŒÖ t	        j>                  |d	«      }t	        j@                  |d	«      }||z
  d|z  k  }g }g }g }tC        t1        |«      «      D ]†  }||d	f   sŒ||d
f   sŒ|j=                  ||   «       |j=                  | j&                  ||   j4                     j6                  «       |j=                  |||   j8                     j6                  «       Œˆ t	        j.                  |«      }t	        j.                  |«      }|j                   d	   dkD  rft        jD                  ||t        jF                  «      \  }}| j                  dkD  rD|dxx   | j                  z  cc<   |dxx   | j                  z  cc<   ntI        jJ                  d«       |j#                  «       | _        t#        j"                  |«      | _        t#        j"                  |«      | _        |S )ax  Apply feature-based methods like ORB or SIFT to a raw frame.

        Args:
            raw_frame (np.ndarray): The raw frame to be processed, with shape (H, W, C).
            detections (list, optional): List of detections to be used in the processing.

        Returns:
            (np.ndarray): Transformation matrix with shape (2, 3).

        Examples:
            >>> gmc = GMC(method="orb")
            >>> raw_frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)
            >>> transformation_matrix = gmc.apply_features(raw_frame)
            >>> print(transformation_matrix.shape)
            (2, 3)
        r   r=   rH   éÿ   r   g\�Âõ(\ï?Né   r   r   Tg      Ð?gÍÌÌÌÌÌì?g      @©r   r=   ©r   r=   únot enough matching points)&rI   r    rJ   rK   rA   rB   r   rN   Ú
zeros_likeÚintÚastypeÚint_r"   Údetectr$   Úcomputer5   rO   r2   r3   r4   r'   ÚknnMatchÚarrayÚlenÚdistanceÚqueryIdxÚptÚtrainIdxÚabsÚappendÚmeanÚstdÚrangeÚestimateAffinePartial2DÚRANSACr   rR   )r6   rC   rD   rS   rT   rU   rV   rW   ÚmaskÚdetÚtlbrÚ	keypointsÚdescriptorsÚ
knnMatchesÚmatchesÚspatialDistancesÚmaxSpatialDistanceÚmÚnÚprevKeyPointLocationÚcurrKeyPointLocationÚspatialDistanceÚmeanSpatialDistancesÚstdSpatialDistancesÚinliersÚgoodMatchesÚ
prevPointsÚ
currPointsÚis                                r:   r>   zGMC.apply_features—   s¿  € ð" %Ÿ?™?Ñˆ��qØ?@ÀAºv”—‘˜Y¬×(:Ñ(:Ô;È9ˆÜ�F‰F�1�a‹Lˆð �>‰>˜CÒÜ—J‘J˜u u°·±Ñ'>ÀÈ$Ï.É.Ñ@XÐ&YÓZˆEØ˜TŸ^™^Ñ+ˆEØ˜tŸ~™~Ñ-ˆFô �}‰}˜UÓ#ˆØ_bˆŒS�˜‘Ó¤# d¨V¡mÓ"4Ð4´c¸$À¹,Ó6GÌ#ÈdÐUZÉlÓJ[Ð6[Ð[Ñ\ð Ð!Ø!ò ?�Ø˜B˜Q˜ $§.¡.Ñ0×8Ñ8¼¿¹ÓA�Ø=>��T˜!‘W˜t A™wÐ&¨¨Q©°$°q±'Ð(9Ð9Ò:ð?ð
 —M‘M×(Ñ(¨°Ó5ˆ	Ø!%§¡×!7Ñ!7¸¸yÓ!IÑˆ	�;ð ×)Ò)Ø"ŸZ™Z›\ˆDŒNÜ!%§¡¨9Ó!5ˆDÔÜ#'§9¡9¨[Ó#9ˆDÔ Ø)-ˆDÔ&ØˆHð —\‘\×*Ñ*¨4×+?Ñ+?ÀÈaÓPˆ
ð ˆØÐØ!¤B§H¡H¨e°V¨_Ó$=Ñ=Ðô ˆz‹?˜aÒØ"ŸZ™Z›\ˆDŒNÜ!%§¡¨9Ó!5ˆDÔÜ#'§9¡9¨[Ó#9ˆDÔ ØˆHð ò 	&‰DˆAˆqØ�z‰z˜C !§*¡*Ñ,Ó,Ø'+×'9Ñ'9¸!¿*¹*Ñ'E×'HÑ'HÐ$Ø'0°·±Ñ'<×'?Ñ'?Ð$ð )¨Ñ+Ð.BÀ1Ñ.EÑEØ(¨Ñ+Ð.BÀ1Ñ.EÑEð#�ô
 —F‘F˜?¨1Ñ-Ó.Ð1CÀAÑ1FÓFÜ—F‘F˜?¨1Ñ-Ó.Ð1CÀAÑ1FÓFà$×+Ñ+¨OÔ<Ø—N‘N 1Õ%ð	&ô"  "Ÿw™wÐ'7¸Ó;ÐÜ Ÿf™fÐ%5°qÓ9ÐØ#Ð&:Ñ:¸cÐDWÑ>WÑWˆð ˆØˆ
Øˆ
Ü”s˜7“|Ó$ò 	EˆAØ�q˜!�t‹} ¨¨A¨£Ø×"Ñ" 7¨1¡:Ô.Ø×!Ñ! $×"4Ñ"4°W¸Q±Z×5HÑ5HÑ"I×"LÑ"LÔMØ×!Ñ! )¨G°A©J×,?Ñ,?Ñ"@×"CÑ"CÕDð		Eô —X‘X˜jÓ)ˆ
Ü—X‘X˜jÓ)ˆ
ð ×Ñ˜AÑ Ò"Ü×4Ñ4°ZÀÌSÏZÉZÓX‰JˆAˆwð �~‰~ Ò#Ø�$“˜4Ÿ>™>Ñ)“Ø�$“˜4Ÿ>™>Ñ)”ä�N‰NÐ7Ô8ð Ÿ™›ˆŒÜ!ŸY™Y yÓ1ˆÔÜ#Ÿy™y¨Ó5ˆÔàˆr;   c                ó"  — |j                   \  }}}|dk(  r$t        j                  |t        j                  «      n|}t	        j
                  dd«      }| j                  dkD  r2t        j                  ||| j                  z  || j                  z  f«      }t        j                  |fddi| j                  ¤Ž}| j                  r| j                  €8|j                  «       | _        t        j                  |«      | _        d| _
        |S t        j                  | j                  || j                  d«      \  }}	}
g }g }t        t!        |	«      «      D ]:  }|	|   sŒ	|j#                  | j                  |   «       |j#                  ||   «       Œ< t	        j$                  |«      }t	        j$                  |«      }|j                   d   dkD  r…|j                   d   |j                   d   k(  rft        j&                  ||t        j(                  «      \  }}
| j                  dkD  rD|d	xx   | j                  z  cc<   |d
xx   | j                  z  cc<   nt+        j,                  d«       |j                  «       | _        t        j                  |«      | _        |S )aä  Apply Sparse Optical Flow method to a raw frame.

        Args:
            raw_frame (np.ndarray): The raw frame to be processed, with shape (H, W, C).

        Returns:
            (np.ndarray): Transformation matrix with shape (2, 3).

        Examples:
            >>> gmc = GMC()
            >>> result = gmc.apply_sparseoptflow(np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]))
            >>> print(result)
            [[1. 0. 0.]
             [0. 1. 0.]]
        r   r=   rH   rt   NTr   r\   r]   r^   r_   )rI   r    rJ   rK   rA   rB   r   rN   ÚgoodFeaturesToTrackr0   r5   r3   rO   r2   ÚcalcOpticalFlowPyrLKrq   rh   rn   rg   rr   rs   r   rR   )r6   rC   rS   rT   rU   rV   rW   rw   ÚmatchedKeypointsÚstatusrX   r†   r‡   rˆ   s                 r:   r@   zGMC.apply_sparseoptflow  s.  € ð  %Ÿ?™?Ñˆ��qØ?@ÀAºv”—‘˜Y¬×(:Ñ(:Ô;È9ˆÜ�F‰F�1�a‹Lˆð �>‰>˜CÒÜ—J‘J˜u u°·±Ñ'>ÀÈ$Ï.É.Ñ@XÐ&YÓZˆEô ×+Ñ+¨EÑT¸ÐTÀ×@SÑ@SÑTˆ	ð ×)Ò)¨T×-?Ñ-?Ð-GØ"ŸZ™Z›\ˆDŒNÜ!%§¡¨9Ó!5ˆDÔØ)-ˆDÔ&ØˆHô '*×&>Ñ&>¸t¿~¹~ÈuÐVZ×VhÑVhÐjnÓ&oÑ#Ð˜& !ð ˆ
Øˆ
ä”s˜6“{Ó#ò 	7ˆAØ�a‹yØ×!Ñ! $×"4Ñ"4°QÑ"7Ô8Ø×!Ñ!Ð"2°1Ñ"5Õ6ð	7ô
 —X‘X˜jÓ)ˆ
Ü—X‘X˜jÓ)ˆ
ð ×Ñ˜QÑ !Ò#¨*×*:Ñ*:¸1Ñ*=À×AQÑAQÐRSÑATÒ*TÜ×.Ñ.¨z¸:ÄsÇzÁzÓR‰DˆAˆqð �~‰~ Ò#Ø�$“˜4Ÿ>™>Ñ)“Ø�$“˜4Ÿ>™>Ñ)”ä�N‰NÐ7Ô8ð Ÿ™›ˆŒÜ!ŸY™Y yÓ1ˆÔàˆr;   c                ó<   — d| _         d| _        d| _        d| _        y)zSReset the internal parameters including previous frame, keypoints, and descriptors.NF)r2   r3   r4   r5   )r6   s    r:   Úreset_paramszGMC.reset_paramsN  s!   € àˆŒØ!ˆÔØ#ˆÔØ%*ˆÕ"r;   )r   r=   )r   Ústrr   ra   Úreturnr   )N)rC   ú
np.ndarrayrD   zlist | Noner‘   r’   )rC   r’   r‘   r’   )r‘   r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   rE   r?   r>   r@   r�   Ú__classcell__)r9   s   @r:   r   r      s,   ø„ ñö:)+ôV ó4%ôNsój@÷D+r;   r   )	Ú
__future__r   rO   r    ÚnumpyrA   Úultralytics.utilsr   r   © r;   r:   ú<module>rœ      s"   ðõ #ã ã 
Û å $÷F+ò F+r;   