
    a6d8                         d Z ddlmZ ddlmZ ddlZddl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 Zddddddej        ddZd Zddddej        ddZdS )z.TV-L1 optical flow algorithm implementation.

    )partial)combinations_with_replacementN)ndimage   )gaussian)_supported_float_type)warp   )coarse_to_fineget_warp_pointsc	                   ! | j         !t          j        !fd| j        D             ddd}	d| j        z  }
d}||z  }|
|z  }|| j        z  }|x}}t          j        | j        f| j        z   !          }t          j        | j        | j        f| j        z   !          }t          d          g|j        z  }t          d          g|j        z  }t          d          g|j        dz
  z  }t          |          D ]p}|r"t          j
        |d	g| j        d
gz  z             }t          |t          |	|          d          }t          j        t          j        |                    }||z                      d          }d	||dk    <   || z
  ||z                      d          z
  }t          |          D ]}|||z                      d          z   }t!          |          ||z  k    }|}|dd|fxx         ||         |dd|f         z  ||         z  z  cc<   | }|t          j        ||                   z  }|dd|fxx         ||dd|f         z  z  cc<   |                                }t          | j                  D ]}||d<   t          |          D ]}t          | j                  D ]^}||d<   t          dd          ||d	z   <   t          j        ||         |          |t)          |          <   t          d          ||d	z   <   _t          j        |dz                      d                    t          j        df         }||z  }|dz  }||xx         |
|z  z  cc<   ||xx         |z  cc<   ||                             d           } t          | j                  D ]}||d	<   t          dd          ||dz   <   t          d	d          ||<   | t)          |          xx         |t)          |                   z  cc<   t          d          ||dz   <   t          d          ||<   ||         | z   ||<   ||z  }||z                                  |k     r n|}r|S )u  TV-L1 solver for optical flow estimation.

    Parameters
    ----------
    reference_image : ndarray, shape (M, N[, P[, ...]])
        The first gray scale image of the sequence.
    moving_image : ndarray, shape (M, N[, P[, ...]])
        The second gray scale image of the sequence.
    flow0 : ndarray, shape (image0.ndim, M, N[, P[, ...]])
        Initialization for the vector field.
    attachment : float
        Attachment parameter. The smaller this parameter is,
        the smoother is the solutions.
    tightness : float
        Tightness parameter. It should have a small value in order to
        maintain attachment and regularization parts in
        correspondence.
    num_warp : int
        Number of times moving_image is warped.
    num_iter : int
        Number of fixed point iteration.
    tol : float
        Tolerance used as stopping criterion based on the L² distance
        between two consecutive values of (u, v).
    prefilter : bool
        Whether to prefilter the estimated optical flow before each
        image warp.

    Returns
    -------
    flow : ndarray, shape ((image0.ndim, M, N[, P[, ...]])
        The estimated optical flow components for each axis.

    c                 <    g | ]}t          j        |           S dtypenparange.0nr   s     Blib/python3.11/site-packages/skimage/registration/_optical_flow.py
<listcomp>z_tvl1.<locals>.<listcomp>7   8     9 9 9 1E222 9 9 9    ijTindexingsparseg      ?r   r   Nr
      edgemoder   axis.g      ?)r   r   meshgridshapendimsizezerosslicerangendimedian_filterr	   r   arraygradientsumabssigncopydifftuplesqrtnewaxis)"reference_imagemoving_imageflow0
attachment	tightnessnum_warpnum_itertol	prefiltergriddtreg_num_iterf0f1flow_currentflow_previousgprojs_gs_ps_d_image1_warpgradNIrho_0rhoidxflow_auxiliarysrhoaxnormdr   s"                                    @r   _tvl1r[      s   J !E; 9 9 9 9"1"79 9 9 $T3 3 3D 
#	#BL	i	B	iB?C#((L=
/&(?+@@NNNA8_)?+?A%+,38: : :D ;;/AF
"C;;/DI
%C;;/TYq[
)C8__ ?% ?% 	O,\./S?3G1#3M-MO OL <|)L)L &( ( (xK00114i__Q27o-1D0I0I!0L0LLx ,	@ ,	@A 4,11!444Cc((b2g%C)N111c6"""c#htAAAsF|&;BsG&CC"""$CC)))D111c6"""d43<&77""" *..00L_122 @ @A|,, @ @A#O$899 0 0!#A$)!RLLBqD	(*S0A(K(K(K%**$)$KKBqD		7AF<<??33BJODDBJDBJDIIIa'IIIIII%III cq)))A#O$899 . .!#A$)!RLLBqD	"'4..B%**eCjj)99$)$KKBqD	"'++B(6s(;a(?L%%/@@6 	%-',,..44E$r      g333333?   
   g-C6?F)r=   r>   r?   r@   rA   rB   r   c          	          t          t          ||||||          }	t          j        |          t	          |          k    rd| d}
t          |
          t          | ||	|          S )u  Coarse to fine optical flow estimator.

    The TV-L1 solver is applied at each level of the image
    pyramid. TV-L1 is a popular algorithm for optical flow estimation
    introduced by Zack et al. [1]_, improved in [2]_ and detailed in [3]_.

    Parameters
    ----------
    reference_image : ndarray, shape (M, N[, P[, ...]])
        The first gray scale image of the sequence.
    moving_image : ndarray, shape (M, N[, P[, ...]])
        The second gray scale image of the sequence.
    attachment : float, optional
        Attachment parameter (:math:`\lambda` in [1]_). The smaller
        this parameter is, the smoother the returned result will be.
    tightness : float, optional
        Tightness parameter (:math:`\tau` in [1]_). It should have
        a small value in order to maintain attachment and
        regularization parts in correspondence.
    num_warp : int, optional
        Number of times moving_image is warped.
    num_iter : int, optional
        Number of fixed point iteration.
    tol : float, optional
        Tolerance used as stopping criterion based on the L² distance
        between two consecutive values of (u, v).
    prefilter : bool, optional
        Whether to prefilter the estimated optical flow before each
        image warp. When True, a median filter with window size 3
        along each axis is applied. This helps to remove potential
        outliers.
    dtype : dtype, optional
        Output data type: must be floating point. Single precision
        provides good results and saves memory usage and computation
        time compared to double precision.

    Returns
    -------
    flow : ndarray, shape ((image0.ndim, M, N[, P[, ...]])
        The estimated optical flow components for each axis.

    Notes
    -----
    Color images are not supported.

    References
    ----------
    .. [1] Zach, C., Pock, T., & Bischof, H. (2007, September). A
       duality based approach for realtime TV-L 1 optical flow. In Joint
       pattern recognition symposium (pp. 214-223). Springer, Berlin,
       Heidelberg. :DOI:`10.1007/978-3-540-74936-3_22`
    .. [2] Wedel, A., Pock, T., Zach, C., Bischof, H., & Cremers,
       D. (2009). An improved algorithm for TV-L 1 optical flow. In
       Statistical and geometrical approaches to visual motion analysis
       (pp. 23-45). Springer, Berlin, Heidelberg.
       :DOI:`10.1007/978-3-642-03061-1_2`
    .. [3] Pérez, J. S., Meinhardt-Llopis, E., & Facciolo,
       G. (2013). TV-L1 optical flow estimation. Image Processing On
       Line, 2013, 137-150. :DOI:`10.5201/ipol.2013.26`

    Examples
    --------
    >>> from skimage.color import rgb2gray
    >>> from skimage.data import stereo_motorcycle
    >>> from skimage.registration import optical_flow_tvl1
    >>> image0, image1, disp = stereo_motorcycle()
    >>> # --- Convert the images to gray level: color is not supported.
    >>> image0 = rgb2gray(image0)
    >>> image1 = rgb2gray(image1)
    >>> flow = optical_flow_tvl1(image1, image0)

    )r=   r>   r?   r@   rA   rB   dtype=. is not supported. Try 'float32' or 'float64.'r   )r   r[   r   r   r   
ValueErrorr   )r:   r;   r=   r>   r?   r@   rA   rB   r   solvermsgs              r   optical_flow_tvl1re      sz    Z Uz(8h	3 3 3F 
x/6666LuLLLoo/<uMMMMr   c                    | j         | j        }d|z  dz   }|r!||dz  fz  }	t          t          |	d          }
n t          t          j        ||fz  d          }
|}t          j        | j        ||fz             }t          j        | j        |fz             }t          j	        fd| j        D             d	d
d}t          |          D ]}|rt	          j        |d|dz  z             }t          |t          ||          d          }t          j        t          j        |          d          }||z                      d          | z   |z
  }t#          t          |          d          D ]-\  }} |
||         ||         z            x|d||f<   |d||f<   .t          |          D ]} |
||         |z            |d|f<   t%          t          j                            |                    dk     }t          j        |          ||<   d||<   t          j        t          j                            ||          |d          }|S )a  Iterative Lucas-Kanade (iLK) solver for optical flow estimation.

    Parameters
    ----------
    reference_image : ndarray, shape (M, N[, P[, ...]])
        The first gray scale image of the sequence.
    moving_image : ndarray, shape (M, N[, P[, ...]])
        The second gray scale image of the sequence.
    flow0 : ndarray, shape (reference_image.ndim, M, N[, P[, ...]])
        Initialization for the vector field.
    radius : int
        Radius of the window considered around each pixel.
    num_warp : int
        Number of times moving_image is warped.
    gaussian : bool
        if True, a gaussian kernel is used for the local
        integration. Otherwise, a uniform kernel is used.
    prefilter : bool
        Whether to prefilter the estimated optical flow before each
        image warp. This helps to remove potential outliers.

    Returns
    -------
    flow : ndarray, shape ((reference_image.ndim, M, N[, P[, ...]])
        The estimated optical flow components for each axis.

    r   r
      mirror)sigmar#   )r*   r#   r   c                 <    g | ]}t          j        |           S r   r   r   s     r   r   z_ilk.<locals>.<listcomp>  r   r   r   Tr   )r
   )r    r!   r"   r   r%   .g+=)r   r)   r   gaussian_filterr.   uniform_filterr   r+   r(   r'   r-   r/   r	   r   stackr1   r2   r   r3   linalgdeteyemoveaxissolve)r:   r;   r<   radiusr?   r   rB   r)   r*   ri   filter_funcflowAbrC   rO   moving_image_warprQ   error_imageijrU   r   s                         @r   _ilkr|      s   : !EDv:>D -q|#oUJJJc0tth#+- - - D 	&$5UCCCA
&$1???A; 9 9 9 9"1"79 9 9 $T3 3 3D 8__ ; ; 	A$T54%<+?@@D tT/J/J&,. . .x$566Q???t((a(00()+<= 2%++qAA 	I 	IDAq*5+d1gQ6G*H*HHAc1aiL1S!QY<<t 	; 	;A#DGk$9::Ac1fII ")--""##e+E***## {29??1a00$::Kr      )rs   r?   r   rB   r   c                    t          t          ||||          }t          j        |          t	          |          k    rd| d}t          |          t          | |||          S )a<
  Coarse to fine optical flow estimator.

    The iterative Lucas-Kanade (iLK) solver is applied at each level
    of the image pyramid. iLK [1]_ is a fast and robust alternative to
    TVL1 algorithm although less accurate for rendering flat surfaces
    and object boundaries (see [2]_).

    Parameters
    ----------
    reference_image : ndarray, shape (M, N[, P[, ...]])
        The first gray scale image of the sequence.
    moving_image : ndarray, shape (M, N[, P[, ...]])
        The second gray scale image of the sequence.
    radius : int, optional
        Radius of the window considered around each pixel.
    num_warp : int, optional
        Number of times moving_image is warped.
    gaussian : bool, optional
        If True, a Gaussian kernel is used for the local
        integration. Otherwise, a uniform kernel is used.
    prefilter : bool, optional
        Whether to prefilter the estimated optical flow before each
        image warp. When True, a median filter with window size 3
        along each axis is applied. This helps to remove potential
        outliers.
    dtype : dtype, optional
        Output data type: must be floating point. Single precision
        provides good results and saves memory usage and computation
        time compared to double precision.

    Returns
    -------
    flow : ndarray, shape ((reference_image.ndim, M, N[, P[, ...]])
        The estimated optical flow components for each axis.

    Notes
    -----
    - The implemented algorithm is described in **Table2** of [1]_.
    - Color images are not supported.

    References
    ----------
    .. [1] Le Besnerais, G., & Champagnat, F. (2005, September). Dense
       optical flow by iterative local window registration. In IEEE
       International Conference on Image Processing 2005 (Vol. 1,
       pp. I-137). IEEE. :DOI:`10.1109/ICIP.2005.1529706`
    .. [2] Plyer, A., Le Besnerais, G., & Champagnat,
       F. (2016). Massively parallel Lucas Kanade optical flow for
       real-time video processing applications. Journal of Real-Time
       Image Processing, 11(4), 713-730. :DOI:`10.1007/s11554-014-0423-0`

    Examples
    --------
    >>> from skimage.color import rgb2gray
    >>> from skimage.data import stereo_motorcycle
    >>> from skimage.registration import optical_flow_ilk
    >>> reference_image, moving_image, disp = stereo_motorcycle()
    >>> # --- Convert the images to gray level: color is not supported.
    >>> reference_image = rgb2gray(reference_image)
    >>> moving_image = rgb2gray(moving_image)
    >>> flow = optical_flow_ilk(moving_image, reference_image)

    )rs   r?   r   rB   r`   ra   r   )r   r|   r   r   r   rb   r   )	r:   r;   rs   r?   r   rB   r   rc   rd   s	            r   optical_flow_ilkr   6  su    F T&8h(* * *F 
x/6666LuLLLoo/<uMMMMr   )__doc__	functoolsr   	itertoolsr   numpyr   scipyr   r.   _shared.filtersr   rk   _shared.utilsr   	transformr	   _optical_flow_utilsr   r   r[   float32re   r|   r    r   r   <module>r      s@          3 3 3 3 3 3                 9 9 9 9 9 9 1 1 1 1 1 1       @ @ @ @ @ @ @ @{ { {@ "$sQ%rzUN UN UN UN UNpL L L` U$BJJN JN JN JN JN JN JNr   