
    ^j1                     4   d dl mZ d dlmZmZ d dlmZ ddlm	Z	 ddl
mZ ddlmZmZ ddlmZmZmZmZmZmZmZmZ dd	lmZmZ dd
lmZmZmZ  e       rd dlZerddl m!Z!  G d ded      Z"d Z#defdZ$	 	 ddZ%	 	 	 	 ddZ&e G d de	             Z'dgZ(y)    )TYPE_CHECKING)Image	ImageDraw)
functional   )TorchvisionBackend)BatchFeature)group_images_by_shapereorder_images)
ImageInput	ImageTypePILImageResamplingSizeDictget_image_typeis_pil_imageis_valid_imageto_numpy_array)ImagesKwargsUnpack)
TensorTypeauto_docstringis_torch_availableN   )$EfficientLoFTRKeypointMatchingOutputc                       e Zd ZU dZeed<   y)"EfficientLoFTRImageProcessorKwargsz
    do_grayscale (`bool`, *optional*, defaults to `self.do_grayscale`):
        Whether to convert the image to grayscale. Can be overridden by `do_grayscale` in the `preprocess` method.
    do_grayscaleN)__name__
__module____qualname____doc__bool__annotations__     /var/www/ramen.bs-engineer-server.com/venv/lib/python3.12/site-packages/transformers/models/efficientloftr/image_processing_efficientloftr.pyr   r   $   s    
 r%   r   F)totalc                     t        |       xsC t        |       xr6 t        |       t        j                  k7  xr t        | j                        dk(  S )Nr   r   r   r   r   PILlenshapeimages    r&   _is_valid_imager/   -   sF     ub."79=="HbSQVQ\Q\M]abMbr%   imagesc                     d}d t        | t              rQt        |       dk(  rt        fd| D              r| S t        fd| D              r| D cg c]  }|D ]  }|  c}}S t	        |      c c}}w )N)z-Input images must be a one of the following :z - A pair of PIL images.z - A pair of 3D arrays.z! - A list of pairs of PIL images.z  - A list of pairs of 3D arrays.c                     t        |       xsC t        |       xr6 t        |       t        j                  k7  xr t        | j                        dk(  S )z$images is a PIL Image or a 3D array.r   r)   r-   s    r&   r/   z8validate_and_format_image_pairs.<locals>._is_valid_image<   sG    E" 
5!fnU&;y}}&LfQTUZU`U`QaefQf	
r%      c              3   .   K   | ]  } |        y wNr$   .0r.   r/   s     r&   	<genexpr>z2validate_and_format_image_pairs.<locals>.<genexpr>C   s     #Q_U%;#Q   c              3      K   | ]:  }t        |t              xr$ t        |      d k(  xr t        fd|D               < yw)r3   c              3   .   K   | ]  } |        y wr5   r$   r6   s     r&   r8   z<validate_and_format_image_pairs.<locals>.<genexpr>.<genexpr>H   s     CuOE*Cr9   N)
isinstancelistr+   all)r7   
image_pairr/   s     r&   r8   z2validate_and_format_image_pairs.<locals>.<genexpr>E   sN      
  z4( DJ1$DC
CCD
s   A A)r<   r=   r+   r>   
ValueError)r0   error_messager?   r.   r/   s       @r&   validate_and_format_image_pairsrB   3   s    M
 &$v;!#Q&#Q QM 
 %	
 
 -3Kj
KuEKEKK
]
## Ls   A3c           	      $   | j                   dk  s#| j                  | j                   dk(  rdnd   dk(  ryt        j                  | ddddddf   | ddddddf   k(        xr. t        j                  | ddddddf   | ddddddf   k(        S )zAChecks if an image is grayscale (all RGB channels are identical).r   r   r   T.Nr3   )ndimr,   torchr>   r-   s    r&   is_grayscalerF   O   s     zzA~%**/QqAQF99U31a<(E#q!Q,,??@ UYYc1aluS!Q\22F r%   c                 J    t        |       r| S t        j                  | d      S )a  
    Converts an image to grayscale format using the NTSC formula. Only support torch.Tensor.

    This function is supposed to return a 1-channel image, but it returns a 3-channel image with the same value in each
    channel, because of an issue that is discussed in :
    https://github.com/huggingface/transformers/pull/25786#issuecomment-1730176446

    Args:
        image (torch.Tensor):
            The image to convert.
    r   )num_output_channels)rF   tvFrgb_to_grayscaler-   s    r&   convert_to_grayscalerK   Z   s$     E1==r%   c                   x    e Zd ZeZej                  ZdddZdZ	dZ
dZdZdZdZdee   f fd	Zed
edee   def fd       Zd
edefdZ	 d"d
ed   dededddedededz  deez  dz  dedefdZ	 d#dddeee   z  dedeeeej@                  f      fdZ!deeeej@                  f      ded   fd Z"d! Z# xZ$S )$EfficientLoFTRImageProcessori  i  )heightwidthFTgp?Nkwargsc                 $    t        |   di | y )Nr$   )super__init__)selfrP   	__class__s     r&   rS   z%EfficientLoFTRImageProcessor.__init__y   s    "6"r%   r0   returnc                 $    t        |   |fi |S r5   )rR   
preprocess)rT   r0   rP   rU   s      r&   rX   z'EfficientLoFTRImageProcessor.preprocess|   s    w!&3F33r%   c                 :    | j                  |      }t        |      S r5   )fetch_imagesrB   )rT   r0   rP   s      r&   _prepare_images_structurez6EfficientLoFTRImageProcessor._prepare_images_structure   s     ""6*.v66r%   torch.Tensor	do_resizesizeresamplez7PILImageResampling | tvF.InterpolationMode | int | None
do_rescalerescale_factordisable_groupingreturn_tensorsr   c
                 (   t        ||      \  }}i }|j                         D ]   \  }}|r| j                  |||      }|||<   " t        ||      }t        ||      \  }}i }|j                         D ]+  \  }}|r| j	                  ||      }|	rt        |      }|||<   - t        ||      }t        dt        |      d      D cg c]
  }|||dz     }}|D cg c]  }t        j                  |d       }}t        d|i|      S c c}w c c}w )N)rb   )r^   r_   r   r3   )dimpixel_values)datatensor_type)r
   itemsresizer   rescalerK   ranger+   rE   stackr	   )rT   r0   r]   r^   r_   r`   ra   rb   rc   r   rP   grouped_imagesgrouped_images_indexprocessed_images_groupedr,   stacked_imagesresized_imagesprocessed_imagesiimage_pairspairstacked_pairss                         r&   _preprocessz(EfficientLoFTRImageProcessor._preprocess   sS    0EV^n/o,,#% %3%9%9%; 	=!E>!%^$QY!Z.<$U+	= ((@BVW/D^fv/w,,#% %3%9%9%; 	=!E>!%nn!M!5n!E.<$U+	= **BDXY =B!SIYEZ\]<^_q'AE2__ ?JJdTq1JJ .-!@n]] ` Ks   D
Doutputsr   target_sizes	thresholdc                 4   |j                   j                  d   t        |      k7  rt        d      t	        d |D              st        d      t        |t              r,t        j                  ||j                   j                        }n1|j                  d   dk7  s|j                  d   dk7  rt        d      |}|j                  j                         }||j                  d      j                  dddd      z  }|j                  t        j                        }g }t!        ||j                   |j"                        D ]X  \  }}}	t        j$                  |	|kD  |dkD        }
|d   |
d      }|d   |
d      }|	d   |
d      }|j'                  |||d	       Z |S )
a  
        Converts the raw output of [`EfficientLoFTRKeypointMatchingOutput`] into lists of keypoints, scores and descriptors
        with coordinates absolute to the original image sizes.
        Args:
            outputs ([`EfficientLoFTRKeypointMatchingOutput`]):
                Raw outputs of the model.
            target_sizes (`torch.Tensor` or `List[Tuple[Tuple[int, int]]]`, *optional*):
                Tensor of shape `(batch_size, 2, 2)` or list of tuples of tuples (`Tuple[int, int]`) containing the
                target size `(height, width)` of each image in the batch. This must be the original image size (before
                any processing).
            threshold (`float`, *optional*, defaults to 0.0):
                Threshold to filter out the matches with low scores.
        Returns:
            `List[Dict]`: A list of dictionaries, each dictionary containing the keypoints in the first and second image
            of the pair, the matching scores and the matching indices.
        r   zRMake sure that you pass in as many target sizes as the batch dimension of the maskc              3   8   K   | ]  }t        |      d k(    yw)r3   N)r+   )r7   target_sizes     r&   r8   zNEfficientLoFTRImageProcessor.post_process_keypoint_matching.<locals>.<genexpr>   s     I[3{#q(Is   zTEach element of target_sizes must contain the size (h, w) of each image of the batch)devicer   r3   )
keypoints0
keypoints1matching_scores)matchesr,   r+   r@   r>   r<   r=   rE   tensorr   	keypointscloneflipreshapetoint32zipr   logical_andappend)rT   ry   rz   r{   image_pair_sizesr   resultskeypoints_pairr   scoresvalid_matchesmatched_keypoints0matched_keypoints1r   s                 r&   post_process_keypoint_matchingz;EfficientLoFTRImageProcessor.post_process_keypoint_matching   s   , ??  #s<'88qrrILIIsttlD)$||LAWAWX!!!$)\-?-?-Ba-G j   ,%%++-	 0 5 5b 9 A A"aA NN	LL-	/29goowOfOf/g 	+NGV!--fy.@'B,OM!/!2=3C!D!/!2=3C!D$Qia(89ONN"4"4'6	  r%   keypoint_matching_outputzImage.Imagec           	      <   t        |      }|D cg c]  }t        |       }}t        dt        |      d      D cg c]
  }|||dz     }}g }t	        ||      D ]  \  }}|d   j
                  dd \  }	}
|d   j
                  dd \  }}t        j                  t        |	|      |
|z   dft        j                        }t        j                  |d         |d|	d|
f<   t        j                  |d         |d||
df<   t        j                  |j                               }t        j                  |      }|d   j!                  d      \  }}|d   j!                  d      \  }}t	        |||||d	         D ]  \  }}}}}| j#                  |      }|j%                  ||||
z   |f|d
       |j'                  |dz
  |dz
  |dz   |dz   fd       |j'                  ||
z   dz
  |dz
  ||
z   dz   |dz   fd        |j)                  |        |S c c}w c c}w )a  
        Plots the image pairs side by side with the detected keypoints as well as the matching between them.

        Args:
            images:
                Image pairs to plot. Same as `EfficientLoFTRImageProcessor.preprocess`. Expects either a list of 2
                images or a list of list of 2 images list with pixel values ranging from 0 to 255.
            keypoint_matching_output (List[Dict[str, torch.Tensor]]]):
                A post processed keypoint matching output

        Returns:
            `List[PIL.Image.Image]`: A list of PIL images, each containing the image pairs side by side with the detected
            keypoints as well as the matching between them.
        r   r3   Nr   r   )dtyper   r   r   )fillrO   black)r   )rB   r   rl   r+   r   r,   rE   zerosmaxuint8
from_numpyr   	fromarraynumpyr   Drawunbind
_get_colorlineellipser   )rT   r0   r   r.   rt   ru   r   r?   pair_outputheight0width0height1width1
plot_imageplot_image_pildrawkeypoints0_xkeypoints0_ykeypoints1_xkeypoints1_ykeypoint0_xkeypoint0_ykeypoint1_xkeypoint1_ymatching_scorecolors                             r&   visualize_keypoint_matchingz8EfficientLoFTRImageProcessor.visualize_keypoint_matching   sh   ( 185;<E.'<<273v;2JKQva!a%(KK'*;8P'Q 	+#J(m11"15OGV(m11"15OGVc'7&;Vf_a%PX]XcXcdJ,1,<,<Z],KJxx&(),1,<,<Z],KJxx()"__Z-=-=-?@N>>.1D)4\)B)I)I!)L&L,)4\)B)I)I!)L&L,VYlL,TeHfW R[+{N 7		 +{V/C[Q  
 kAo{QaQ\_`Q`ahop 6)A-{Qf@TWX@XZehiZij    NN>*7	+8 A =Ks
   HHc                 N    t        dd|z
  z        }t        d|z        }d}|||fS )zMaps a score to a color.   r   r   )int)rT   scorergbs        r&   r   z'EfficientLoFTRImageProcessor._get_color&  s3    q5y!"e!Qwr%   )T)g        )%r   r   r    r   valid_kwargsr   BILINEARr_   r^   default_to_squarer]   r`   ra   do_normalizer   r   rS   r   r   r	   rX   r[   r=   r"   r   floatstrr   rx   tupledictrE   Tensorr   r   r   __classcell__)rU   s   @r&   rM   rM   m   s   5L!**HC(DIJNLL#(J!K # 4 4v>`7a 4fr 4 477 
	7& ")^^$)^ )^ 	)^
 L)^ )^ )^ +)^ j(4/)^ )^ 
)^^ 	979 !4;.9 	9
 
d3$%	&9v5 #'tC,='>"?5 
m		5nr%   rM   )r.   r\   )r.   r\   rV   r\   ))typingr   r*   r   r   torchvision.transforms.v2r   rI   image_processing_backendsr   image_processing_utilsr	   image_transformsr
   r   image_utilsr   r   r   r   r   r   r   r   processing_utilsr   r   utilsr   r   r   rE   modeling_efficientloftrr   r   r/   rB   rF   rK   rM   __all__r$   r%   r&   <module>r      s    !   7 ; 2 E	 	 	 5 C C MU $J $8>>>& }#5 } }@ *
*r%   