o
    Wh8                     @   s6   d dl Z d dlZd dlZd dlmZ G dd dZdS )    N)LOGGERc                       s   e Zd ZdZddededdf fdd	Zdd
ejde	dejfddZ
d
ejdejfddZdd
ejde	dejfddZd
ejdejfddZdddZ  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): 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): Previous frame for tracking.
        prevKeyPoints (list): Keypoints from the previous frame.
        prevDescriptors (np.ndarray): 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.array([[1, 2, 3], [4, 5, 6]])
        >>> processed_frame = gmc.apply(frame)
        >>> print(processed_frame)
        array([[1, 2, 3],
               [4, 5, 6]])
    sparseOptFlow   method	downscalereturnNc                    s  t    || _td|| _| jdkr&td| _t | _	t
tj| _nX| jdkrEtjdddd| _tjdddd| _	t
tj| _n9| jdkr]d	}d
}tj| _tjtjB ||f| _n!| jdkrntddddddd| _n| jdv rwd| _ntd| d| _d| _d| _d| _dS )a  
        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.

        Examples:
            Initialize a GMC object with the 'sparseOptFlow' method and a downscale factor of 2
            >>> gmc = GMC(method="sparseOptFlow", downscale=2)
           orb   sift   {Gz?)nOctaveLayerscontrastThresholdedgeThresholdecci  gư>r   i  g{Gz?Fg{Gz?)
maxCornersqualityLevelminDistance	blockSizeuseHarrisDetectork>   NNonenoneNzUnknown GMC method: )super__init__r   maxr   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__ R/var/www/vscode/kcb/lib/python3.10/site-packages/ultralytics/trackers/utils/gmc.pyr   +   s6   








zGMC.__init__	raw_frame
detectionsc                 C   sJ   | j dv r| ||S | j dkr| |S | j dkr| |S tddS )ag  
        Apply object detection on a raw frame using the specified method.

        Args:
            raw_frame (np.ndarray): The raw frame to be processed, with shape (H, W, C).
            detections (List | None): 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   )r   apply_features	apply_eccapply_sparseoptflownpeye)r4   r;   r<   r9   r9   r:   apply[   s   




z	GMC.applyc              
   C   s   |j \}}}t|tj}tjddtjd}| jdkr0t|dd}t	||| j || j f}| j
s=| | _d| _
|S zt| j||| j| jdd	\}}W |S  tyk } ztd
|  W Y d}~|S d}~ww )a3  
        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,find transform failed. Set warp as identity )shaper   cvtColorCOLOR_BGR2GRAYr@   rA   float32r   GaussianBlurresizer3   copyr0   findTransformECCr)   r,   	Exceptionr   warning)r4   r;   heightwidth_frameHer9   r9   r:   r>   v   s$   

"zGMC.apply_eccc                 C   sv  |j \}}}t|tj}tdd}| jdkr0t||| j || j f}|| j }|| j }t|}d|t	d| t	d| t	d| t	d| f< |durw|D ]!}	|	dd | j 
tj}
d	||
d
 |
d |
d	 |
d f< qU| j||}| j||\}}| js| | _t|| _t|| _d| _|S | j| j|d}g }g }dt||g }t|d	kr| | _t|| _t|| _|S |D ]L\}}|jd|j k r| j|j j}||j j}|d	 |d	  |d
 |d
  f}t|d	 |d	 k rt|d
 |d
 k r|| || qt|d	}t |d	}|| d| k }g }g }g }t!t|D ]/}||d	f rl||d
f rl|||  || j|| j j |||| j j q>t|}t|}|j d	 dkrt"||tj#\}}| jdkr|d  | j9  < |d  | j9  < nt$%d | | _t|| _t|| _|S )a~  
        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 | None): 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   rD      r   g\(\?N   r   r	   Tg      ?g?g      @r   r   r	   r   not enough matching points)&rE   r   rF   rG   r@   rA   r   rJ   
zeros_likeintastypeint_r    detectr"   computer3   rK   r0   r1   r2   r%   knnMatcharraylendistancequeryIdxpttrainIdxabsappendmeanstdrangeestimateAffinePartial2DRANSACr   rN   )r4   r;   r<   rO   rP   rQ   rR   rS   maskdettlbr	keypointsdescriptors
knnMatchesmatchesspatialDistancesmaxSpatialDistancemnprevKeyPointLocationcurrKeyPointLocationspatialDistancemeanSpatialDistancesstdSpatialDistancesinliersgoodMatches
prevPoints
currPointsir9   r9   r:   r=      s   



4&







zGMC.apply_featuresc                 C   s  |j \}}}t|tj}tdd}| jdkr&t||| j || j f}tj|fddi| j	}| j
r:| jdu rJ| | _t|| _d| _
|S t| j|| jd\}}	}g }
g }tt|	D ]}|	| rv|
| j|  |||  qat|
}
t|}|
j d dkr|
j d |j d krt|
|tj\}}| jdkr|d	  | j9  < |d
  | j9  < ntd | | _t|| _|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   rD   rn   NTr   rV   rW   rX   rY   )rE   r   rF   rG   r@   rA   r   rJ   goodFeaturesToTrackr.   r3   r1   rK   r0   calcOpticalFlowPyrLKrk   rb   rh   ra   rl   rm   r   rN   )r4   r;   rO   rP   rQ   rR   rS   rq   matchedKeypointsstatusr   r   r   r9   r9   r:   r?   2  s>   



"


zGMC.apply_sparseoptflowc                 C   s   d| _ d| _d| _d| _dS )zSReset the internal parameters including previous frame, keypoints, and descriptors.NF)r0   r1   r2   r3   )r4   r9   r9   r:   reset_paramss  s   
zGMC.reset_params)r   r   )N)r   N)__name__
__module____qualname____doc__strr[   r   r@   ndarraylistrB   r>   r=   r?   r   __classcell__r9   r9   r7   r:   r      s    0- Ar   )rK   r   numpyr@   ultralytics.utilsr   r   r9   r9   r9   r:   <module>   s
   