
    3j#                         S SK JrJrJr  S SKrS SKJr  S SKJr  S SKJ	r	J
r
  S SKJr  S SKJr  S SKJr   " S	 S
\R"                  5      rg)    )DictOptionalTupleN)nn)rgb_to_grayscale)LocalFeatureMatcherLoFTR)find_homography_dlt_iterated)RANSAC)warp_perspectivec                   P  ^  \ rS rSrSrS"S\R                  S\S\SS4U 4S jjjrS	\	R                  S
\	R                  S\	R                  4S jrS\	R                  S\	R                  S\	R                  4S jrS\	R                  S\	R                  S\	R                  S\	R                  4S jrS\	R                  S\	R                  S\\\	R                  4   4S jrS\	R                  S\	R                  S\	R                  4S jrS\\\	R                  4   S\\\	R                  4   4S jr  S#S\	R                  S\	R                  S\\	R                     S\\	R                     S\\	R                  \	R                  4   4
S jjrS\	R                  S\	R                  4S  jrS!rU =r$ )$ImageStitcher   a  Stitch two images with overlapping fields of view.

Args:
    matcher: image feature matching module.
    estimator: method to compute homography, either "vanilla" or "ransac".
        "ransac" is slower with a better accuracy.
    blending_method: method to blend two images together.
        Only "naive" is currently supported.

Note:
    Current implementation requires strict image ordering from left to right.

.. code-block:: python

    IS = ImageStitcher(KF.LoFTR(pretrained='outdoor'), estimator='ransac').cuda()
    # Compute the stitched result with less GPU memory cost.
    with torch.inference_mode():
        out = IS(img_left, img_right)
    # Show the result
    plt.imshow(K.tensor_to_image(out))

matcher	estimatorblending_methodreturnNc                    > [         TU ]  5         Xl        X l        X0l        US;  a  [        SU S35      eUS:X  a  [        S5      U l        g g )N)ransacvanillaUnsupported estimator $. Use `ransac` or `vanilla` instead.r   
homography)super__init__r   r   r   NotImplementedErrorr   r   )selfr   r   r   	__class__s       X/home/wildlama/miniconda3/lib/python3.13/site-packages/kornia/contrib/image_stitching.pyr   ImageStitcher.__init__6   sV    ".11%(>ykIm&noo  .DK !    
keypoints1
keypoints2c           
      
   U R                   S:X  a1  [        US   US   [        R                  " USSS2S4   5      5      nU$ U R                   S:X  a  U R	                  X!5      u  p4US   nU$ [        SU R                    S35      e)zEstimate homography by the matched keypoints.

Args:
    keypoints1: matched keypoint set from an image, shaped as :math:`(N, 2)`.
    keypoints2: matched keypoint set from the other image, shaped as :math:`(N, 2)`.

r   Nr   r   r   r   )r   r
   torch	ones_liker   r   )r   r"   r#   homo_s        r   _estimate_homography"ImageStitcher._estimate_homography@   s     >>Y&/4 *T"2EOOJtUVXYzDZ4[D  ^^x'kk*9GD:D  &(>t~~>NNr&sttr!   argskwargsc           	         US   US   US   pTn[        [        UR                  5       5      5       Vs/ s H  o`R                  X5U:H     XEU:H     5      PM      nn[        U5      S:X  a  [	        S5      e[
        R                  " U5      $ s  snf )z%Compute the corresponding homography.
keypoints0r"   batch_indexesr   z6Compute homography failed. No matched keypoints found.)rangelenuniquer)   RuntimeErrorr%   cat)r   r+   r,   kp1kp2idxihomoss           r   estimate_transform ImageStitcher.estimate_transformS   s    |,f\.BF?D[#RWX[\_\f\f\hXiRjkRjQ**3ax=#Qh-HRjku:?WXXyy ls   %B
src_imgdst_imgmaskc                     U R                   S:X  a  [        R                  " US:H  X5      nU$ [        SU R                    S35      e)zBlend two images together.naive   zUnsupported blending method z. Use `naive`.)r   r%   wherer   )r   r<   r=   r>   outs        r   blend_imageImageStitcher.blend_image]   sL     7*++dai:C 
 &(DTEYEYDZZh&ijjr!   image_1image_2c                     [        U R                  [        [        45      (       a  [	        U5      [	        U5      S.nU$ [        SU R                   S35      e)z(Preprocess input to the required format.)image0image1zThe preprocessor for z has not been implemented.)
isinstancer   r	   r   r   r   )r   rF   rG   
input_dicts       r   
preprocessImageStitcher.preprocessf   sV     dllU,?$@AA*73*73J  &(=dll^Ke&fggr!   imagec                     UR                  S5      n[        UR                  5       R                  S5      R	                  5       R                  5       R                  5       5      nUS:X  a  U$ USSU24   $ )a4  Crop redundant empty columns from a stitched panorama.

Args:
    image: Stitched image tensor, typically shaped
        :math:`(B, C, H, W_{panorama})`, where ``W_{panorama}`` is the
        panorama width after concatenation/warping.
    mask: Validity mask aligned with ``image`` where non-zero values mark
        pixels covered by at least one input view.

Returns:
    The stitched image cropped to remove trailing invalid columns
    (columns that contain no valid pixels in the mask).
    If no redundant area is found, the original ``image`` is returned.
)r   rA   r   .N)sumintboolanylongargminitem)r   rO   r>   mask_indexs        r   postprocessImageStitcher.postprocessr   sg       EJJL$$Q',,.557<<>?A:LS&5&[!!r!   datac                 $    U R                  U5      $ )aR  Run the configured feature matcher on preprocessed inputs.

Args:
    data: Matcher input dictionary, usually containing ``image0`` and
        ``image1`` tensors.

Returns:
    A correspondence dictionary produced by ``self.matcher``.
    Typical entries are matched keypoints and batch indices used later
    for homography estimation.
)r   )r   r\   s     r   
on_matcherImageStitcher.on_matcher   s     ||D!!r!   images_leftimages_right	mask_left
mask_rightc                    U R                  X5      nUR                  S   UR                  S   UR                  S   -   4nU R                  U5      nU R                  " S0 UD6n[	        X(U5      n	[
        R                  " U[
        R                  " U5      /S5      n
Uc  [
        R                  " U5      nUc  [
        R                  " U5      n[	        XHUSS9n[
        R                  " U[
        R                  " U5      /S5      nU R                  XU5      X-   R                  5       R                  UR                  5      4$ )a  Stitch two images into a shared panorama frame.

Args:
    images_left: Reference image tensor, shaped :math:`(B, C, H, W_l)`.
    images_right: Image tensor to be warped onto the reference frame,
        shaped :math:`(B, C, H, W_r)`.
    mask_left: Optional validity mask for ``images_left`` with the same
        shape as ``images_left``.
    mask_right: Optional validity mask for ``images_right`` with the same
        shape as ``images_right``.

Returns:
    A tuple ``(stitched_image, stitched_mask)``:
    - ``stitched_image`` is the blended panorama tensor with width
      ``W_l + W_r`` before final cropping.
    - ``stitched_mask`` is a mask tensor indicating which panorama
      pixels are valid after warping and blending.
nearest)mode )rM   shaper^   r:   r   r%   r4   
zeros_liker&   rD   rS   todtype)r   r`   ra   rb   rc   rL   	out_shapecorrespondencesr'   r<   r=   src_maskdst_masks                r   stitch_pairImageStitcher.stitch_pair   s   4 __[?
 &&r*K,=,=b,ALDVDVWYDZ,Z[	//*5&&99"<yA))[%*:*:<*HI2N 4I6J#JiiP99i)9)9*)EFK(;h>Q=W=W=Y=\=\]e]k]k=lllr!   imgsc                     US   n[         R                  " U5      n[        [        U5      S-
  5       H  nU R	                  X!US-      U5      u  p#M     U R                  X#5      $ )a  Iteratively stitch a sequence of overlapping images.

Args:
    *imgs: Ordered image tensors from left to right. Each tensor is expected
        to share a common height and overlap with the next image.
        Each tensor typically follows :math:`(B, C, H, W)`.

Returns:
    A single panorama tensor obtained by stitching all provided images
    in order and cropping trailing empty space.
r   rA   )r%   r&   r0   r1   rr   rZ   )r   rt   img_outrb   r8   s        r   forwardImageStitcher.forward   sb     q'OOG,	s4y1}%A!%!1!1'A;	!RGY &33r!   )r   r   r   r   )r   r@   )NN)__name__
__module____qualname____firstlineno____doc__r   Modulestrr   r%   Tensorr)   r:   rD   r   rM   rZ   r^   r   r   rr   rw   __static_attributes____classcell__)r   s   @r   r   r      s   ./		 /c /WZ /im / /u||  Z_ZfZf &     QVQ]Q]  5<< %,, ell _d_k_k 
%,, 
 
$sTYT`T`O`Ja 
" "U\\ "ell ","tC$56 "4U\\@Q;R "$ -1-1)m\\)m ll)m ELL)	)m
 U\\*)m 
u||U\\)	*)mV4U\\ 4ell 4 4r!   r   )typingr   r   r   r%   r   kornia.colorr   kornia.featurer   r	   kornia.geometry.homographyr
   kornia.geometry.ransacr   kornia.geometry.transformr   r~   r   ri   r!   r   <module>r      s4   $ ) (   ) 5 C ) 6s4BII s4r!   