a
    dA                  	   @   s(  d Z ddlmZ ddlZddlmZ ddlm  mZ ddl	m
Z
 ddlmZ ddlmZmZmZmZmZ ddlmZ dd	lmZmZmZmZ g d
ZdejejeejdddZdejejeejdddZdejejejejeejdddZG dd dej Z!deeejeje"e"edddZ#dS )z8Module containing operators to work on RGB-Depth images.    )UnionN)spatial_gradient)create_meshgrid   )PinholeCamera	cam2pixel	pixel2camproject_pointsunproject_points)normalize_pixel_coordinates)compose_transformationsconvert_points_to_homogeneousinverse_transformationtransform_points)depth_to_3ddepth_to_normalswarp_frame_depth
depth_warpDepthWarperF)depthcamera_matrixnormalize_pointsreturnc           
      C   s  t | tjs tdt|  dt| jdkr<| jd dksLtd| j t |tjsltdt| dt|jdkr|jd	d
 dkstd|j d| j\}}}}t||dd}|	| j
	| j}| dddd}|d
d
d
d
f }t||||d}	|	ddddS )a  Compute a 3d point per pixel given its depth value and the camera intrinsics.

    Args:
        depth: image tensor containing a depth value per pixel with shape :math:`(B, 1, H, W)`.
        camera_matrix: tensor containing the camera intrinsics with shape :math:`(B, 3, 3)`.
        normalize_points: whether to normalise the pointcloud. This must be set to `True` when the depth is
          represented as the Euclidean ray length from the camera position.

    Return:
        tensor with a 3d point per pixel of the same resolution as the input :math:`(B, 3, H, W)`.

    Example:
        >>> depth = torch.rand(1, 1, 4, 4)
        >>> K = torch.eye(3)[None]
        >>> depth_to_3d(depth, K).shape
        torch.Size([1, 3, 4, 4])
    ,Input depht type is not a torch.Tensor. Got .   r   2Input depth musth have a shape (B, 1, H, W). Got: 4Input camera_matrix type is not a torch.Tensor. Got    Nr   r   6Input camera_matrix must have a shape (B, 3, 3). Got: FZnormalized_coordinatesr      )	normalize)
isinstancetorchTensor	TypeErrortypelenshape
ValueErrorr   todevicedtypepermuter
   )
r   r   r   _heightwidthZ	points_2dZpoints_depthcamera_matrix_tmpZ	points_3d r6   ^/var/www/html/stable-diffusion-webui/venv/lib/python3.9/site-packages/kornia/geometry/depth.pyr      s"     r   c                 C   s   t | tjs tdt|  dt| jdkr<| jd dksLtd| j t |tjsltdt| dt|jdkr|jd	d
 dkstd|j dt| ||}t	|}|d
d
d
d
df |d
d
d
d
df  }}tj
||dd}tj|dddS )a  Compute the normal surface per pixel.

    Args:
        depth: image tensor containing a depth value per pixel with shape :math:`(B, 1, H, W)`.
        camera_matrix: tensor containing the camera intrinsics with shape :math:`(B, 3, 3)`.
        normalize_points: whether to normalise the pointcloud. This must be set to `True` when the depth is
        represented as the Euclidean ray length from the camera position.

    Return:
        tensor with a normal surface vector per pixel of the same resolution as the input :math:`(B, 3, H, W)`.

    Example:
        >>> depth = torch.rand(1, 1, 4, 4)
        >>> K = torch.eye(3)[None]
        >>> depth_to_normals(depth, K).shape
        torch.Size([1, 3, 4, 4])
    r   r   r   r   r   r   r   r   r    Nr!   r"   r   dimr$   )r9   p)r&   r'   r(   r)   r*   r+   r,   r-   r   r   ZcrossFr%   )r   r   r   ZxyzZ	gradientsabZnormalsr6   r6   r7   r   A   s     .r   )	image_src	depth_dstsrc_trans_dstr   r   r   c                 C   s  t | tjs tdt|  dt| jdks>td| j t |tjs^tdt| dt|jdkrz|jd dkstd|j t |tjstd	t| dt|jd
kr|jdd dkstd|j dt |tjstdt| dt|jd
kr |jdd dks2td|j dt|||}|	ddd
d}t
|dddf |}|ddddf }t||}|jdd \}	}
t||	|
}tj| |ddS )ac  Warp a tensor from a source to destination frame by the depth in the destination.

    Compute 3d points from the depth, transform them using given transformation, then project the point cloud to an
    image plane.

    Args:
        image_src: image tensor in the source frame with shape :math:`(B,D,H,W)`.
        depth_dst: depth tensor in the destination frame with shape :math:`(B,1,H,W)`.
        src_trans_dst: transformation matrix from destination to source with shape :math:`(B,4,4)`.
        camera_matrix: tensor containing the camera intrinsics with shape :math:`(B,3,3)`.
        normalize_points: whether to normalise the pointcloud. This must be set to ``True`` when the depth
           is represented as the Euclidean ray length from the camera position.

    Return:
        the warped tensor in the source frame with shape :math:`(B,3,H,W)`.
    z0Input image_src type is not a torch.Tensor. Got r   r   z6Input image_src musth have a shape (B, D, H, W). Got: z0Input depht_dst type is not a torch.Tensor. Got r   r   z6Input depth_dst musth have a shape (B, 1, H, W). Got: z4Input src_trans_dst type is not a torch.Tensor. Got r   r    N)r   r   z6Input src_trans_dst must have a shape (B, 4, 4). Got: r   r!   r"   r   r$   Talign_corners)r&   r'   r(   r)   r*   r+   r,   r-   r   r1   r   r	   r   r;   grid_sample)r>   r?   r@   r   r   Zpoints_3d_dstZpoints_3d_srcr5   Zpoints_2d_srcr3   r4   Zpoints_2d_src_normr6   r6   r7   r   l   s0     $
r   c                       s   e Zd ZdZdeeeeeed fddZe	eee
jdd	d
Zed dddZdd Ze
jdddZe
je
jdddZe
je
je
jdddZ  ZS )r   aB  Warp a patch by depth.

    .. math::
        P_{src}^{\{dst\}} = K_{dst} * T_{src}^{\{dst\}}

        I_{src} = \\omega(I_{dst}, P_{src}^{\{dst\}}, D_{src})

    Args:
        pinholes_dst: the pinhole models for the destination frame.
        height: the height of the image to warp.
        width: the width of the image to warp.
        mode: interpolation mode to calculate output values ``'bilinear'`` | ``'nearest'``.
        padding_mode: padding mode for outside grid values ``'zeros'`` | ``'border'`` | ``'reflection'``.
        align_corners: interpolation flag.
    bilinearzerosT)pinhole_dstr3   r4   modepadding_moderB   c                    sR   t    || _|| _|| _|| _d| _|| _|| _d | _	d | _
| ||| _d S )Ngư>)super__init__r4   r3   rG   rH   ZepsrB   _pinhole_dst_pinhole_src_dst_proj_src_create_meshgridgrid)selfrF   r3   r4   rG   rH   rB   	__class__r6   r7   rJ      s    	
zDepthWarper.__init__)r3   r4   r   c                 C   s   t | |dd}t|S )NFr#   )r   r   )r3   r4   rO   r6   r6   r7   rN      s    zDepthWarper._create_meshgrid)pinhole_srcr   c                 C   sp   t | jts tdt| jt |ts<tdt|t| jjt|j}t	
| jj|}|| _|| _| S )zCCompute the projection matrix from the source to destination frame.zFMember self._pinhole_dst expected to be of class PinholeCamera. Got {}zBArgument pinhole_src expected to be of class PinholeCamera. Got {})r&   rK   r   r)   formatr*   r   Z
extrinsicsr   r'   matmulZ
intrinsicsrL   rM   )rP   rS   Zdst_trans_srcZdst_proj_srcr6   r6   r7   compute_projection_matrix   s"    
z%DepthWarper.compute_projection_matrixc                 C   s   | j d u s| jd u rtdtj|g|g|gdggg| j j| j jd}t| j |}d|d d df  }|d d df | }|d d df | }t||gdS )N'Please, call compute_projection_matrix.      ?r/   r0   r$   r   r   )	rM   rL   r-   r'   Ztensorr/   r0   rU   cat)rP   xyZinvdZpointZflowzr6   r6   r7   _compute_projection   s     zDepthWarper._compute_projection)r   c                 C   sn   d}|  | jd | jd d| }|  | jd | jd d| }tj|| dddd }|| }td| S )a1  Compute the required inverse depth step to achieve sub pixel accurate sampling of the depth cost volume,
        per camera.

        Szeliski, Richard, and Daniel Scharstein. "Symmetric sub-pixel stereo matching." European Conference on Computer
        Vision. Springer Berlin Heidelberg, 2002.
        g{Gz?r$   rX   r8   g       @g      ?)r^   r4   r3   r'   Znormmin)rP   Zdelta_dZxy_m1Zxy_p1ZdxZdxddr6   r6   r7   compute_subpixel_step  s    z!DepthWarper.compute_subpixel_step)	depth_srcr   c           
      C   s   | j du s| jdu rtdt|jdkr:td|j|j\}}}}|j}|j}| jj	||d
|ddd}t|| j j	||d|}t|| j j	||d}t|| j| j}	|	S )aT  Compute a grid for warping a given the depth from the reference pinhole camera.

        The function `compute_projection_matrix` has to be called beforehand in order to have precomputed the relative
        projection matrices encoding the relative pose and the intrinsics between the reference and a non reference
        camera.
        NrW   r   z9Input depth_src has to be in the shape of Bx1xHxW. Got {}rY   r_   )rM   rL   r-   r+   r,   rT   r/   r0   rO   r.   expandr   Zintrinsics_inverser   r   r3   r4   )
rP   rb   Z
batch_sizer2   r/   r0   Zpixel_coordsZcam_coords_srcZpixel_coords_srcZpixel_coords_src_normr6   r6   r7   	warp_grid  s     zDepthWarper.warp_grid)rb   	patch_dstr   c                 C   s    t j|| || j| j| jdS )a  Warp a tensor from destination frame to reference given the depth in the reference frame.

        Args:
            depth_src: the depth in the reference frame. The tensor must have a shape :math:`(B, 1, H, W)`.
            patch_dst: the patch in the destination frame. The tensor must have a shape :math:`(B, C, H, W)`.

        Return:
            the warped patch from destination frame to reference.

        Shape:
            - Output: :math:`(N, C, H, W)` where C = number of channels.

        Example:
            >>> # pinholes camera models
            >>> pinhole_dst = PinholeCamera(torch.randn(1, 4, 4), torch.randn(1, 4, 4),
            ... torch.tensor([32]), torch.tensor([32]))
            >>> pinhole_src = PinholeCamera(torch.randn(1, 4, 4), torch.randn(1, 4, 4),
            ... torch.tensor([32]), torch.tensor([32]))
            >>> # create the depth warper, compute the projection matrix
            >>> warper = DepthWarper(pinhole_dst, 32, 32)
            >>> _ = warper.compute_projection_matrix(pinhole_src)
            >>> # warp the destination frame to reference by depth
            >>> depth_src = torch.ones(1, 1, 32, 32)  # Nx1xHxW
            >>> image_dst = torch.rand(1, 3, 32, 32)  # NxCxHxW
            >>> image_src = warper(depth_src, image_dst)  # NxCxHxW
        )rG   rH   rB   )r;   rC   rd   rG   rH   rB   )rP   rb   re   r6   r6   r7   forward7  s    zDepthWarper.forward)rD   rE   T)__name__
__module____qualname____doc__r   intstrboolrJ   staticmethodr'   r(   rN   rV   r^   ra   rd   rf   __classcell__r6   r6   rQ   r7   r      s&      $r   T)rF   rS   rb   re   r3   r4   rB   c                 C   s$   t | |||d}|| |||S )a  Function that warps a tensor from destination frame to reference given the depth in the reference frame.

    See :class:`~kornia.geometry.warp.DepthWarper` for details.

    Example:
        >>> # pinholes camera models
        >>> pinhole_dst = PinholeCamera(torch.randn(1, 4, 4), torch.randn(1, 4, 4),
        ... torch.tensor([32]), torch.tensor([32]))
        >>> pinhole_src = PinholeCamera(torch.randn(1, 4, 4), torch.randn(1, 4, 4),
        ... torch.tensor([32]), torch.tensor([32]))
        >>> # warp the destination frame to reference by depth
        >>> depth_src = torch.ones(1, 1, 32, 32)  # Nx1xHxW
        >>> image_dst = torch.rand(1, 3, 32, 32)  # NxCxHxW
        >>> image_src = depth_warp(pinhole_dst, pinhole_src, depth_src, image_dst, 32, 32)  # NxCxHxW
    rA   )r   rV   )rF   rS   rb   re   r3   r4   rB   Zwarperr6   r6   r7   r   [  s    
r   )F)F)F)T)$rj   typingr   r'   Ztorch.nnnnZtorch.nn.functionalZ
functionalr;   Zkornia.filters.sobelr   Zkornia.utilsr   Zcamerar   r   r   r	   r
   Zconversionsr   Zlinalgr   r   r   r   __all__r(   rm   r   r   r   Moduler   rk   r   r6   r6   r6   r7   <module>   sB   /0 B 5 