o
    :ήc6                     @   sf   d Z ddlZddlmZmZmZ ddlmZ 	dddZdd	 Z	d
d Z
ddddddddddZdS )z
Port of Manuel Guizar's code from:
http://www.mathworks.com/matlabcentral/fileexchange/18401-efficient-subpixel-image-registration-by-cross-correlation
    N)fftnifftnfftfreq   )_masked_phase_cross_correlationc           
      C   s   t |ds|g| j }nt|| jkrtd|du r"dg| j }nt|| jkr-tddtj }tt| j||}|ddd D ]/\}}}t	|| dddf t
|| }	t| |	 }	|	j| jdd	}	tj|	| d
d} qB| S )a  
    Upsampled DFT by matrix multiplication.

    This code is intended to provide the same result as if the following
    operations were performed:
        - Embed the array "data" in an array that is ``upsample_factor`` times
          larger in each dimension.  ifftshift to bring the center of the
          image to (1,1).
        - Take the FFT of the larger array.
        - Extract an ``[upsampled_region_size]`` region of the result, starting
          with the ``[axis_offsets+1]`` element.

    It achieves this result by computing the DFT in the output array without
    the need to zeropad. Much faster and memory efficient than the zero-padded
    FFT approach if ``upsampled_region_size`` is much smaller than
    ``data.size * upsample_factor``.

    Parameters
    ----------
    data : array
        The input data array (DFT of original data) to upsample.
    upsampled_region_size : integer or tuple of integers, optional
        The size of the region to be sampled.  If one integer is provided, it
        is duplicated up to the dimensionality of ``data``.
    upsample_factor : integer, optional
        The upsampling factor.  Defaults to 1.
    axis_offsets : tuple of integers, optional
        The offsets of the region to be sampled.  Defaults to None (uses
        image center)

    Returns
    -------
    output : ndarray
            The upsampled DFT of the specified region.
    __iter__zSshape of upsampled region sizes must be equal to input data's number of dimensions.Nr   zJnumber of axis offsets must be equal to input data's number of dimensions.y               @Fcopy)r   r   )axes)hasattrndimlen
ValueErrornppilistzipshapearanger   expastypedtype	tensordot)
dataupsampled_region_sizeupsample_factoraxis_offsetsim2pidim_propertiesn_itemsups_size	ax_offsetkernel r$   T/tmp/pip-target-vg8gfxp4/lib/python/skimage/registration/_phase_cross_correlation.py_upsampled_dft   s$   
&
r&   c                 C   s   t | j| jS )a  
    Compute global phase difference between the two images (should be
        zero if images are non-negative).

    Parameters
    ----------
    cross_correlation_max : complex
        The complex value of the cross correlation at its maximum point.
    )r   arctan2imagreal)cross_correlation_maxr$   r$   r%   _compute_phasediffQ   s   
r+   c                 C   s(   d| |    ||   }tt|S )a  
    Compute RMS error metric between ``src_image`` and ``target_image``.

    Parameters
    ----------
    cross_correlation_max : complex
        The complex value of the cross correlation at its maximum point.
    src_amp : float
        The normalized average image intensity of the source image
    target_amp : float
        The normalized average image intensity of the target image
    g      ?)conjr   sqrtabs)r*   src_amp
target_amperrorr$   r$   r%   _compute_error^   s   r2   r)   Tg333333?phase)r   spacereturn_errorreference_maskmoving_maskoverlap_rationormalizationc                C   s  |dus|durt | ||||S | j|jkrtd| dkr%| }	|}
n| dkr4t| }	t|}
ntd|	j}|	|
  }|dkr[t|jj	j
}|tt|d|  }n|durctdt|}ttt||j}td	d
 |D }|jj	}t|j|dd}|||k  t|||k 8  < |dkr|rtt|	|	  }||	j }tt|
|
  }||
j }|| }notj||d}t|| | }t|d }t|d }|||  }t| ||| }ttt||j}|| }t|j|dd}||8 }||| 7 }|r9tt|	|	  }tt|
|
  }t|	jD ]}|| dkrKd||< q>|rqt|sbt|sbt|rftd|t|||t|fS |S )u  Efficient subpixel image translation registration by cross-correlation.

    This code gives the same precision as the FFT upsampled cross-correlation
    in a fraction of the computation time and with reduced memory requirements.
    It obtains an initial estimate of the cross-correlation peak by an FFT and
    then refines the shift estimation by upsampling the DFT only in a small
    neighborhood of that estimate by means of a matrix-multiply DFT [1]_.

    Parameters
    ----------
    reference_image : array
        Reference image.
    moving_image : array
        Image to register. Must be same dimensionality as
        ``reference_image``.
    upsample_factor : int, optional
        Upsampling factor. Images will be registered to within
        ``1 / upsample_factor`` of a pixel. For example
        ``upsample_factor == 20`` means the images will be registered
        within 1/20th of a pixel. Default is 1 (no upsampling).
        Not used if any of ``reference_mask`` or ``moving_mask`` is not None.
    space : string, one of "real" or "fourier", optional
        Defines how the algorithm interprets input data. "real" means
        data will be FFT'd to compute the correlation, while "fourier"
        data will bypass FFT of input data. Case insensitive. Not
        used if any of ``reference_mask`` or ``moving_mask`` is not
        None.
    return_error : bool, optional
        Returns error and phase difference if on, otherwise only
        shifts are returned. Has noeffect if any of ``reference_mask`` or
        ``moving_mask`` is not None. In this case only shifts is returned.
    reference_mask : ndarray
        Boolean mask for ``reference_image``. The mask should evaluate
        to ``True`` (or 1) on valid pixels. ``reference_mask`` should
        have the same shape as ``reference_image``.
    moving_mask : ndarray or None, optional
        Boolean mask for ``moving_image``. The mask should evaluate to ``True``
        (or 1) on valid pixels. ``moving_mask`` should have the same shape
        as ``moving_image``. If ``None``, ``reference_mask`` will be used.
    overlap_ratio : float, optional
        Minimum allowed overlap ratio between images. The correlation for
        translations corresponding with an overlap ratio lower than this
        threshold will be ignored. A lower `overlap_ratio` leads to smaller
        maximum translation, while a higher `overlap_ratio` leads to greater
        robustness against spurious matches due to small overlap between
        masked images. Used only if one of ``reference_mask`` or
        ``moving_mask`` is not None.
    normalization : {"phase", None}
        The type of normalization to apply to the cross-correlation. This
        parameter is unused when masks (`reference_mask` and `moving_mask`) are
        supplied.

    Returns
    -------
    shifts : ndarray
        Shift vector (in pixels) required to register ``moving_image``
        with ``reference_image``. Axis ordering is consistent with
        numpy (e.g. Z, Y, X)
    error : float
        Translation invariant normalized RMS error between
        ``reference_image`` and ``moving_image``.
    phasediff : float
        Global phase difference between the two images (should be
        zero if images are non-negative).

    Notes
    -----
    The use of cross-correlation to estimate image translation has a long
    history dating back to at least [2]_. The "phase correlation"
    method (selected by ``normalization="phase"``) was first proposed in [3]_.
    Publications [1]_ and [2]_ use an unnormalized cross-correlation
    (``normalization=None``). Which form of normalization is better is
    application-dependent. For example, the phase correlation method works
    well in registering images under different illumination, but is not very
    robust to noise. In a high noise scenario, the unnormalized method may be
    preferable.

    When masks are provided, a masked normalized cross-correlation algorithm is
    used [5]_, [6]_.

    References
    ----------
    .. [1] Manuel Guizar-Sicairos, Samuel T. Thurman, and James R. Fienup,
           "Efficient subpixel image registration algorithms,"
           Optics Letters 33, 156-158 (2008). :DOI:`10.1364/OL.33.000156`
    .. [2] P. Anuta, Spatial registration of multispectral and multitemporal
           digital imagery using fast Fourier transform techniques, IEEE Trans.
           Geosci. Electron., vol. 8, no. 4, pp. 353–368, Oct. 1970.
           :DOI:`10.1109/TGE.1970.271435`.
    .. [3] C. D. Kuglin D. C. Hines. The phase correlation image alignment
           method, Proceeding of IEEE International Conference on Cybernetics
           and Society, pp. 163-165, New York, NY, USA, 1975, pp. 163–165.
    .. [4] James R. Fienup, "Invariant error metrics for image reconstruction"
           Optics Letters 36, 8352-8357 (1997). :DOI:`10.1364/AO.36.008352`
    .. [5] Dirk Padfield. Masked Object Registration in the Fourier Domain.
           IEEE Transactions on Image Processing, vol. 21(5),
           pp. 2706-2718 (2012). :DOI:`10.1109/TIP.2011.2181402`
    .. [6] D. Padfield. "Masked FFT registration". In Proc. Computer Vision and
           Pattern Recognition, pp. 2918-2925 (2010).
           :DOI:`10.1109/CVPR.2010.5540032`
    Nzimages must be same shapefourierr)   z*space argument must be "real" of "fourier"r3   d   z*normalization must be either phase or Nonec                 S   s   g | ]	}t |d  qS )   )r   fix).0	axis_sizer$   r$   r%   
<listcomp>   s    z+phase_cross_correlation.<locals>.<listcomp>Fr	   r   )r   g      ?g       @r   zNaN values found, please remove NaNs from your input data or use the `reference_mask`/`moving_mask` keywords, eg: phase_cross_correlation(reference_image, moving_image, reference_mask=~np.isnan(reference_image), moving_mask=~np.isnan(moving_image)))r   r   r   lowerr   r,   r   finfor)   r   epsmaximumr.   r   unravel_indexargmaxarraystackr   sumsizeroundceilr=   r&   ranger   isnanr2   r+   )reference_imagemoving_imager   r4   r5   r6   r7   r8   r9   src_freqtarget_freqr   image_productrC   cross_correlationmaxima	midpointsfloat_dtypeshiftsr/   r0   CCmaxr   dftshiftsample_region_offsetdimr$   r$   r%   phase_cross_correlationp   s   j
"

$r]   )r   N)__doc__numpyr   	scipy.fftr   r   r   r   r&   r+   r2   r]   r$   r$   r$   r%   <module>   s    
E