o
    oi[                     @   sn  d Z ddlmZmZ ddl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 ddlmZmZ ddlmZmZ d	d
lmZmZ d	dlmZmZ d	dlmZ g dZd:dej dej deej  dej fddZ!d;dej de"de"de"dej f
ddZ#dej de"dej fddZ$dej d ej d!ej dej fd"d#Z%d$ej deej ej ej f fd%d&Z&d$ej deej ej ej f fd'd(Z'd)ej d*ej d+ej d,ej dej f
d-d.Z(d$ej deej ej f fd/d0Z)	d:d$ej d ej d!ej d1ej d2ej d3eej  deej ej ej f fd4d5Z*d)ej d*ej d+ej d,ej deej ej f f
d6d7Z+	d:dej dej deej  dej fd8d9Z,dS )<z;Module containing functionalities for the Essential matrix.    )OptionalTupleN)eye	ones_likestackwherezeros)KORNIA_CHECKKORNIA_CHECK_SAME_SHAPEKORNIA_CHECK_SHAPE)solvers)eye_likevec_like)_torch_solve_cast_torch_svd_cast   )cross_product_matrixmatrix_cofactor_tensor)depth_from_pointprojection_from_KRt)triangulate_points)decompose_essential_matrix!decompose_essential_matrix_no_svdessential_from_Rtessential_from_fundamentalfind_essentialmotion_from_essential%motion_from_essential_choose_solutionrelative_camera_motionpoints1points2weightsreturnc              
   C   s  t | g d t| | t| jd dkd |dur(t| dddddf | | j\}}}tj| ddd	\}}tj|ddd	\}}t|}	tj|| || ||| || ||||	g	dd
}
|du rk|
dd|
 }
nt	|}|
dd| |
 }
t
|
|}|S )a  Compute the essential matrix using the 5-point algorithm from Nister.

    The linear system is solved by Nister's 5-point algorithm [@nister2004efficient],
    and the solver implemented referred to [@barath2020magsac++][@wei2023generalized][@wang2023vggsfm].

    Args:
        points1: A set of carlibrated points in the first image with a tensor shape :math:`(B, N, 2), N>=8`.
        points2: A set of points in the second image with a tensor shape :math:`(B, N, 2), N>=8`.
        weights: Tensor containing the weights per point correspondence with a shape of :math:`(B, N)`.

    Returns:
        the computed essential matrix with shape :math:`(B, 3, 3)`.

    )BN2r      zNumber of points should be >=5Nr      )dimchunksr)   )r   r
   r	   shapetorchchunkr   cat	transpose
diag_embednull_to_Nister_solution)r   r    r!   
batch_size_x1y1x2y2onesXw_diagE_Nister r>   V/home/ubuntu/.local/lib/python3.10/site-packages/kornia/geometry/epipolar/essential.py
run_5point.   s    
0

r@      null_matijratioc                 C   s   | d d || | f S Nr>   )rB   rC   rD   rE   r>   r>   r?   
fun_select[   s   rG   r;   r4   c           %      C   s  t | \}}}|ddddddf }|ddddddddf }t|dd|j|jd}t|d|j|jd}ttt|d	d
t|d
dtt|d	dt|d
d
 t|dd	ttt|d	dt|d
d	tt|d	d	t|d
d t|dd
 ttt|d	d	t|d
d
tt|d	d
t|d
d	 t|dd |dddf< t	
g dg dg dg}tdD ]E}	tdD ]>}
tt||	d	t||
d	tt||	d
t||
d
 tt||	dt||
d |dd||	|
f ||	|
f d f< qqtdD ]Y}	d|dd|d |	 f |dd|d |	 f  |dd|d |	 f   }|dd|d |	 f  |8  < |dd|d |	 f  |8  < |dd|d |	 f  |8  < qd	}tdD ]k}	tdD ]c}
t|dd||	d	f ||	d	f d f t|d	|
t|dd||	d
f ||	d
f d f t|d
|
 t|dd||	df ||	df d f t|d|
 }||dd|f< |d
7 }qnqh|ddddddf }t	j|ddddddf t	t	j|tt	j|ddddddf d k}| d	kr*t	jd|j|jdd |ddd S t||ddddf || }t	j||ddddf |fdd}|jd	 }t|jd	 dd|j|jd}tdD ]}	d|dd|	d	f< |dddd|	  dd|	  ddf |dd|	|	d
 d
df< |dd|	|	d
 d	df  |dddd|	  dd|	  ddf 8  < d|dd|	df< |dddd|	  dd|	  ddf |dd|	|	d
 ddf< |dd|	|	d
 ddf  |dddd|	  dd|	  ddf 8  < d|dd|	df< |dddd|	  dd|	  ddf |dd|	|	d
 ddf< |dd|	|	d
 ddf  |dddd|	  dd|	  ddf 8  < qct|}t|ddf|j|jd}t|d	d	dd	df jd	 |j|jd}||ddd	dd
df< |dddf d}t	|d	kt	j
d |jd!|}|ddddf  | |dddddf< t	t	j|}|d
}t|dddddd
f |d  |ddddd
df |   |ddd	dddf |  |ddd	dddf  |ddd	dddf |d  |ddd	dddf |   |ddd	dddf |  |ddd	dddf  fd
d}|d
d}|ddd	dddf |d  |ddd	dddf |d   |ddd	ddd"f |   |ddd	dd"df |  |ddd	dddf  d
dd}t	t	j|ddddd	dd	df |ddddd	df }t |dddf d
| |dddf d
 d#k! }t t	|dddddddf d||dddddddf d d#k}|"d"d}t	#|r?t	j$|| \}}t	j%|t	|dd|| } | ||< || }!|!ddd	d
f |ddddd	f   |!ddd
df |ddddd
f    |!ddddf |d  |!ddddf  }"d$t	&|ddddd	f  d |ddddd
f  d  |dd  d$  }#|"|#9 }"|"'|ddddd}"t	jd|"j|"jdd |ddd }$|"|$|< |$S )%a;  Use Nister's 5PC to solve essential matrix.

    The linear system is solved by Nister's 5-point algorithm [@nister2004efficient],
    and the solver implemented referred to [@barath2020magsac++][@wei2023generalized][@wang2023vggsfm].

    Args:
        X: Coefficients for the null space :math:`(B, N, 2), N>=8`.
        batch_size: batcs size of the input, the number of image pairs :math:`B`.

    Returns:
        the computed essential matrix with shape :math:`(B, 3, 3)`.
        Note that the returned E matrices should be the same batch size with the input.

    Nr'   r,   
      devicedtype<   r   r   r(   	   )r   rI   rJ   )rI   (      )rJ   rQ   2   rA         ?)r   r   )r   r   )r(   r(   )rM   rL   r+                 r&                  g:0yE>)rM      gMbP?      ?)(r   r1   r   rL   rM   r   multiply_deg_two_one_polymultiply_deg_one_polyrG   r.   tensorrangelinalgmatrix_rankmaxr   sumr   expandcloner   r0   r-   determinant_to_polynomial	unsqueezer   realeigvalsr   squarematmulinvabsflattensqueezeanyqrsolvesqrtview)%r;   r4   r5   Vnull_	nullSpacecoeffsdindicesrC   rD   tcntrowbsingular_filtereliminated_matcoeffs_batch_size_filteredAcsCeye_matcs_derootsroots_unsquBsbsxzsmaskq_batchr_batchxyz_to_feednullSpace_filteredEsrn   E_returnr>   r>   r?   r3   _   s  "



(L  $666	$2( $
DLDLDP
*,
    
   F<R"**T(r3   F_matK1K2c                 C   s>   t | g d t |g d t |g d |dd|  | S )a  Get Essential matrix from Fundamental and Camera matrices.

    Uses the method from Hartley/Zisserman 9.6 pag 257 (formula 9.12).

    Args:
        F_mat: The fundamental matrix with shape of :math:`(*, 3, 3)`.
        K1: The camera matrix from first camera with shape :math:`(*, 3, 3)`.
        K2: The camera matrix from second camera with shape :math:`(*, 3, 3)`.

    Returns:
        The essential matrix with shape :math:`(*, 3, 3)`.

    *3r   r,   r'   r   r1   )r   r   r   r>   r>   r?   r     s   r   E_matc                 C   s   t | g d t| \}}}|dd}t| }|dddf  d9  < |dd}tt|dk d || |}tt|dk d || |}ttg d	g	| }|d
  d7  < || | }||dd | }	|}
|	}|dddf }|
||fS )a  Decompose an essential matrix to possible rotations and translation.

    This function decomposes the essential matrix E using svd decomposition [96]
    and give the possible solutions: :math:`R1, R2, t`.

    Args:
       E_mat: The essential matrix in the form of :math:`(*, 3, 3)`.

    Returns:
       A tuple containing the first and second possible rotation matrices and the translation vector.
       The shape of the tensors with be same input :math:`[(*, 3, 3), (*, 3, 3), (*, 3, 1)]`.

    r   r,   r'   .Ng      rU   ).NN)rU   rU   r]   ).r(   r(   r]   )
r   r   r1   r   r   r.   detr   r`   type_as)r   Ur5   rw   Vtr   masktWU_W_VtU_Wt_VtR1R2Tr>   r>   r?   r   -  s    
r   c              	   C   s\  t | g d t| jdkr| ddd} | jd }| d | d | d }}}tdtj| | dd	 dd	d
d }tj	tj
j||ddtj
j||ddtj
j||ddgdd}tj|ddd}tj|d	d}|ddddf | | }	|ddd|	d}
tj|	d|
dd}|tj|ddd }tj|ddf| j| jd}|dddf |dddf |dddf }}}| ||ddddf< |ddddf< || |ddddf< |ddddf< | ||ddddf< |ddddf< | }| }t| ||   ||  d }t| ||   ||  d }|||dfS )a4  Decompose the essential matrix to rotation and translation.

       Recover rotation and translation from essential matrices without SVD
      reference: Horn, Berthold KP. Recovering baseline and orientation from essential matrix[J].
      J. Opt. Soc. Am, 1990, 110.

    Args:
       E_mat: The essential matrix in the form of :math:`(*, 3, 3)`.

    Returns:
       A tuple containing the first and second possible rotation matrices and the translation vector.
       The shape of the tensors with be same input :math:`[(*, 3, 3), (*, 3, 3), (*, 3, 1)]`.

    r   rA   r'   r   .r   ).r   ).r(   rS   r,   )dim1dim2r+   r   Tr)   keepdimN)r)   indexrK   r(   )r   lenr-   rv   r.   ru   diagonalr1   re   r   rb   crossnormargmaxri   rf   sizegatherrq   r   rL   rM   r   )r   r#   e1e2e3scale_factorcross_productsnormslargeste_cross_productsindex_expandedb1b1_B1t0t1t2B2b2r   r   r>   r>   r?   r   X  s4   
,24(((""r   r   r   r   r   c                 C   s^   t | g d t |g d t |g d t |g d t| |||\}}t|d }|| S )a  Get the Essential matrix from Camera motion (Rs and ts).

    Reference: Hartley/Zisserman 9.6 pag 257 (formula 9.12)

    Args:
        R1: The first camera rotation matrix with shape :math:`(*, 3, 3)`.
        t1: The first camera translation vector with shape :math:`(*, 3, 1)`.
        R2: The second camera rotation matrix with shape :math:`(*, 3, 3)`.
        t2: The second camera translation vector with shape :math:`(*, 3, 1)`.

    Returns:
        The Essential matrix with the shape :math:`(*, 3, 3)`.

    r   r   r   1r   )r   r   r   )r   r   r   r   Rr}   Txr>   r>   r?   r     s   r   c                 C   sP   t | g d t| \}}}t||||gdd}t|| || gdd}||fS )a  Get Motion (R's and t's ) from Essential matrix.

    Computes and return four possible poses exist for the decomposition of the Essential
    matrix. The possible solutions are :math:`[R1,t], [R1,-t], [R2,t], [R2,-t]`.

    Args:
        E_mat: The essential matrix in the form of :math:`(*, 3, 3)`.

    Returns:
        The rotation and translation containing the four possible combination for the retrieved motion.
        The tuple is as following :math:`[(*, 4, 3, 3), (*, 4, 3, 1)]`.

    r   r+   )r   r   r   )r   r   r   r}   RsTsr>   r>   r?   r     s
   r   r6   r8   r   c                 C   s  t | g d t |g d t |g d t |g d t |g d tt| jdd t|jdd   koBt|jdd kn   |dur]t |ddg t|j|jdd k t| jdk}|r| d } |d }|d }|d }|d }|dur|d }t| \}}td	| }	td	| }
|	dddf dd
dd}	|
dddf dd
dd}
|dddf dd
dd}t||	|
}|}|}|dddf dd
dd}t|||}|dddf dd
dd}|dddf dd
dd}t	||||}t
|	|
|}t
|||}|dk|dk@ }|dur||dM }tj|ddddd }|dd|f ddddf }|dd|f ddddf }|dd|f ddddf }|rf|d }|d }|d }|||fS )a  Recover the relative camera rotation and the translation from an estimated essential matrix.

    The method checks the corresponding points in two images and also returns the triangulated
    3d points. Internally uses :py:meth:`~kornia.geometry.epipolar.decompose_essential_matrix` and then chooses
    the best solution based on the combination that gives more 3d points in front of the camera plane from
    :py:meth:`~kornia.geometry.epipolar.triangulate_points`.

    Args:
        E_mat: The essential matrix in the form of :math:`(*, 3, 3)`.
        K1: The camera matrix from first camera with shape :math:`(*, 3, 3)`.
        K2: The camera matrix from second camera with shape :math:`(*, 3, 3)`.
        x1: The set of points seen from the first camera frame in the camera plane
          coordinates with shape :math:`(*, N, 2)`.
        x2: The set of points seen from the first camera frame in the camera plane
          coordinates with shape :math:`(*, N, 2)`.
        mask: A boolean mask which can be used to exclude some points from choosing
          the best solution. This is useful for using this function with sets of points of
          different cardinality (for instance after filtering with RANSAC) while keeping batch
          semantics. Mask is of shape :math:`(*, N)`.

    Returns:
        The rotation and translation plus the 3d triangulated points.
        The tuple is as following :math:`[(*, 3, 3), (*, 3, 1), (*, N, 3)]`.

    r   )r   r$   r%   Nr,   r   r$   r'   r(   rA   rV   rU   r   Tr   r   )r   r	   r   r-   r   r   r   rf   r   r   r   ri   r.   rd   re   )r   r   r   r6   r8   r   	unbatchedr   tsr   r   P1r   r   P2r;   d1d2
depth_maskmask_indicesR_outt_outpoints3d_outr>   r>   r?   r     s\   !F



r   c                 C   s\   t | g d t |g d t |g d t |g d || dd }|||  }||fS )a  Compute the relative camera motion between two cameras.

    Given the motion parameters of two cameras, computes the motion parameters of the second
    one assuming the first one to be at the origin. If :math:`T1` and :math:`T2` are the camera motions,
    the computed relative motion is :math:`T = T_{2}T^{-1}_{1}`.

    Args:
        R1: The first camera rotation matrix with shape :math:`(*, 3, 3)`.
        t1: The first camera translation vector with shape :math:`(*, 3, 1)`.
        R2: The second camera rotation matrix with shape :math:`(*, 3, 3)`.
        t2: The second camera translation vector with shape :math:`(*, 3, 1)`.

    Returns:
        A tuple with the relative rotation matrix and
        translation vector with the shape of :math:`[(*, 3, 3), (*, 3, 1)]`.

    r   r   r,   r'   r   )r   r   r   r   r   r}   r>   r>   r?   r   =  s   r   c                 C   s   t | ||| j}|S )a{  Find essential matrices.

    Args:
         points1: A set of points in the first image with a tensor shape :math:`(B, N, 2), N>=5`.
         points2: A set of points in the second image with a tensor shape :math:`(B, N, 2), N>=5`.
         weights: Tensor containing the weights per point correspondence with a shape of :math:`(5, N)`.

    Returns:
         the computed essential matrices with shape :math:`(B, 10, 3, 3)`.
         Note that all possible solutions are returned, i.e., 10 essential matrices for each image pair.
         To choose the best one out of 10, try to check the one with the lowest Sampson distance.

    )r@   torM   )r   r    r!   Er>   r>   r?   r   _  s   r   rF   )rA   )-__doc__typingr   r   r.   kornia.corer   r   r   r   r   kornia.core.checkr	   r
   r   kornia.geometryr   kornia.utilsr   r   kornia.utils.helpersr   r   numericr   r   
projectionr   r   triangulationr   __all__Tensorr@   intrG   r3   r   r   r   r   r   r   r   r   r>   r>   r>   r?   <module>   st   ($- ";$$+(E  
i
#