def filters_bank(M, N, J, L=8):
    filters = {}
    filters['psi'] = []

    offset_unpad = 0
    for j in range(J):
        for theta in range(L):
            psi = {}
            psi['j'] = j
            psi['theta'] = theta
            psi_signal = morlet_2d(M, N, 0.8 * 2**j, (int(L - L / 2 - 1) - theta) * np.pi / L, 3.0 / 4.0 * np.pi / 2**j,offset=offset_unpad)  # The 5 is here just to match the LUA implementation :)
            psi_signal_fourier = fft.fft2(psi_signal)
            for res in range(j + 1):
                psi_signal_fourier_res = crop_freq(psi_signal_fourier, res)
                psi[res] = torch.FloatTensor(np.stack((np.real(psi_signal_fourier_res), np.imag(psi_signal_fourier_res)), axis=2))
                # Normalization to avoid doing it with the FFT!
                psi[res].div_(M * N // 2**(2 * j))
            filters['psi'].append(psi)

    filters['phi'] = {}
    phi_signal = gabor_2d(M, N, 0.8 * 2**(J - 1), 0, 0, offset=offset_unpad)
    phi_signal_fourier = fft.fft2(phi_signal)
    filters['phi']['j'] = J
    for res in range(J):
        phi_signal_fourier_res = crop_freq(phi_signal_fourier, res)
        filters['phi'][res] = torch.FloatTensor(np.stack((np.real(phi_signal_fourier_res), np.imag(phi_signal_fourier_res)), axis=2))
        filters['phi'][res].div_(M * N // 2 ** (2 * J))

    return filters
示例#2
0
def phase_cor( A, B ):
  """
  find the 2D correlation between images A and B. This is much faster than any
  of the other scipy correlation methods which insist on working in the spatial
  domain.
  """
  return ( ifft2( fft2(A)*numpy.conj(fft2(B)) ) ).real
示例#3
0
文件: timecrystal.py 项目: natl/bg
 def step4(self):
   '''
   Perform a 4th order timestep
   '''
   
   def order2(c):
     Vc = np.exp( -1j * c * self.dt / 2. * 
                   ( self.V - self.gravity() + 
                     self.g * abs( self.psi ) ** 2
                   )
                 )
     Tc = self.expksquare ** c
     return Vc, Tc
   
   p = 1/(4.-4.**(1/3.))
   q = 1 - 4 * p
   
   Vp,Tp = order2( p )
   Vq,Tq = order2( q )
   
   return Vp * ff.fftshift( ff.ifft2( Tp * ff.fft2( ff.fftshift( Vp ** 2 * 
               ff.fftshift( ff.ifft2( Tp * ff.fft2( ff.fftshift( Vp * Vq *
               ff.fftshift( ff.ifft2( Tq * ff.fft2( ff.fftshift( Vq * Vp * 
               ff.fftshift( ff.ifft2( Tp * ff.fft2( ff.fftshift( Vp ** 2 *  
               ff.fftshift( ff.ifft2( Tp * ff.fft2( ff.fftshift( Vp * self.psi 
               ) ) ) )
               ) ) ) )
               ) ) ) )
               ) ) ) )
               ) ) ) )
示例#4
0
def convolve2D_fft(theta,F):
    func = KS_kernel_real
    #func = gaussian_real

    assert theta.shape == F.shape

    N1,N2 = theta.shape
    
    dtheta1 = theta[1,1].real - theta[0,0].real
    theta1 = dtheta1*(numpy.arange(2*N1)-N1)
    theta1 = fftpack.ifftshift(theta1)
    
    dtheta2 = theta[1,1].imag - theta[0,0].imag
    theta2 = dtheta2*(numpy.arange(2*N2)-N2)
    theta2 = fftpack.ifftshift(theta2)
    
    theta_kernel = numpy.zeros((2*N1,2*N2),dtype=complex)
    theta_kernel += theta1.reshape((2*N1,1))
    theta_kernel += 1j*theta2

    kernel = func(theta_kernel)
    
    dA = dtheta1 * dtheta2

    F_fft = fftpack.fft2(F, (2*N1,2*N2) ) * dA
    F_fft *= fftpack.fft2(kernel,(2*N1,2*N2) ) 
    
    out = fftpack.ifft2(F_fft)
    
    return out[:N1,:N2]
示例#5
0
def drawPic():
    m = 200
    n = 200
    a = 20
    b = 20
    r = 1
    vp0 = 1500
    variance = 0.08
    dx = 3
    C = np.zeros((m, n))

    au = autocorrelation_func(a, b)

    for i in xrange(m):
        for j in xrange(n):
            C[i, j] = au.gaussian((i-(m-1)/2.)*dx, (j-(n-1)/2.)*dx)
    S = fft2(C)  # power spectral density
    z = np.random.randn(m, n)
    Z = fft2(z)

    G = np.sqrt(dx * S)

    GZ = G * Z
    gz = ifft2(GZ)

    A = np.real(gz)

    K = np.real(A)
    f = plt.figure()
    plt.imshow(K)
    return f
示例#6
0
文件: sim.py 项目: msyriac/HaloLenses
    def _storeLensKernel(self):
        '''
        This is an internal function that will store the lensing kernel for the given stamp dimensions
        when the simulator is initialized.
        '''

        N=self.lensN
        scale=self.lensScale

        i=np.array(range(0,N))
        j=np.array(range(0,N))


        xo=(0.5+i-(N)/2.0)  # pixels!
        yo=(0.5+j-(N)/2.0)
        xMesh, yMesh = np.meshgrid(xo,yo)

        r2Mesh = (xMesh**2.+yMesh**2.)

        kX=(1./pi)*xMesh/r2Mesh  # pixels!
        kY=(1./pi)*yMesh/r2Mesh

        
        self.ftKernelX=ff.fft2(kX)
        self.ftKernelY=ff.fft2(kY)
        del(xMesh)
        del(yMesh)
        del(r2Mesh)
        del(kX)
        del(kY)
def filters_bank(M, N, J, L=8):
    filters = {}
    filters['psi'] = []

    offset_unpad = 0
    for j in range(J):
        for theta in range(L):
            psi = {}
            psi['j'] = j
            psi['theta'] = theta
            psi_signal = morlet_2d(M, N, 0.8 * 2**j, (int(L - L / 2 - 1) - theta) * np.pi / L, 3.0 / 4.0 * np.pi / 2**j,offset=offset_unpad)  # The 5 is here just to match the LUA implementation :)
            psi_signal_fourier = fft.fft2(psi_signal)
            for res in range(j + 1):
                psi_signal_fourier_res = crop_freq(psi_signal_fourier, res)
                psi[res] = tf.constant(np.stack((np.real(psi_signal_fourier_res), np.imag(psi_signal_fourier_res)), axis=2))
                psi[res] = tf.div(psi[res], (M * N // 2**(2 * j)), name="psi_theta%s_j%s" % (theta, j))
            filters['psi'].append(psi)

    filters['phi'] = {}
    phi_signal = gabor_2d(M, N, 0.8 * 2**(J - 1), 0, 0, offset=offset_unpad)
    phi_signal_fourier = fft.fft2(phi_signal)
    filters['phi']['j'] = J
    for res in range(J):
        phi_signal_fourier_res = crop_freq(phi_signal_fourier, res)
        filters['phi'][res] = tf.constant(np.stack((np.real(phi_signal_fourier_res), np.imag(phi_signal_fourier_res)), axis=2))
        filters['phi'][res] = tf.div(filters['phi'][res], (M * N // 2 ** (2 * J)), name="phi_res%s" % res)

    return filters
示例#8
0
    def _getCrossCorrelation(self, ref, mask, fft_ref = False, fft_mask = False):
        """ Computes the cross correlation between reference and mask images.
        For parameter description, refer to <self._getDriftValue()> """
        # Images should be square and of same dimensions at this point.
        assert(ref.shape==mask.shape)

        if not fft_ref:
            four_ref = fft2(ref)
        else:
            four_ref = ref

        if not fft_mask:
            # Crop the mask and replace the edges with 0.0 values. Helps the crosscorrelation.
            if self.cropping:
                size = min(mask.shape)
                crop = self.cropping
                mask_cropped = np.copy(mask[crop:(size-crop), crop:(size-crop)])
                mask_padded = np.pad(mask_cropped, crop, mode='constant')
                four_mask = fft2(mask_padded)
            else:
                four_mask = fft2(mask)           
        else:
            four_mask = mask

        # Conjugate the mask.
        four_mask_conj = np.conjugate(four_mask)
        # Compute pointwise product of reference and mask.
        product = np.multiply(four_mask_conj, four_ref)
        # Compute ifft of this product
        xcorr = ifft2(product)
        # Take the absolute value
        xcorr_abs = np.absolute(xcorr)
        return xcorr_abs
def convolution_fourier_RGB(img, fil_fft, fftsize):

    channelR = np.zeros((img.shape[0],img.shape[1]), 'double')
    channelG = np.zeros((img.shape[0],img.shape[1]), 'double')
    channelB = np.zeros((img.shape[0],img.shape[1]), 'double')

    for x in range(img.shape[0]):
        for y in range(img.shape[1]):
            channelR[x,y] = img[x,y][0]
            channelG[x,y] = img[x,y][1]
            channelB[x,y] = img[x,y][2]
        
    matrixR_fft = fftpack.fft2(channelR, (fftsize, fftsize))
    matrixG_fft = fftpack.fft2(channelG, (fftsize, fftsize))
    matrixB_fft = fftpack.fft2(channelB, (fftsize, fftsize))
    
    matrixR_fil_fft = matrixR_fft * fil_fft;
    matrixG_fil_fft = matrixG_fft * fil_fft;
    matrixB_fil_fft = matrixB_fft * fil_fft;

    matrixR_fil = np.real(fftpack.ifft2(matrixR_fil_fft))
    matrixG_fil = np.real(fftpack.ifft2(matrixG_fil_fft))
    matrixB_fil = np.real(fftpack.ifft2(matrixB_fil_fft))
    
    img_fil = np.zeros((matrixR_fil.shape[0], matrixR_fil.shape[1], 3), 'double')

    for x in range(matrixR_fil.shape[0]):
        for y in range(matrixR_fil.shape[1]):
            img_fil[x,y,0] = matrixR_fil[x,y]
            img_fil[x,y,1] = matrixG_fil[x,y]
            img_fil[x,y,2] = matrixB_fil[x,y]
            
    return img_fil
示例#10
0
def mvd_wiener(initImg, imgList, psfList, iterNum, mu, positiveOnly=True):
    if positiveOnly:
        initImg[initImg < 0.0] = 0.0
    viewNum = len(imgList)
    fftFactor = np.sqrt(initImg.shape[0]*initImg.shape[1])
    mu = mu * fftFactor
    I = np.sum(np.abs(initImg))
    e = fft2(initImg)
    e_img_old = initImg
    e_img = initImg
    if iterNum == 0:
        return e_img
    # pre-compute spectra
    ijList = [fft2(img) for img in imgList]
    pjList = [fft2(pad_and_center_psf(psf, initImg.shape)) for psf in psfList]
    for i in xrange(iterNum):
        c_all = np.zeros(e.shape, dtype=float)
        for j in xrange(viewNum):
            ij = ijList[j]
            pj = pjList[j]
            sj = e * pj
            cj = (np.conj(pj) * (ij - sj))/(np.square(np.abs(pj)) + mu**2)
            c_all = c_all + cj / float(viewNum)
        e = e + c_all
        e_img = np.real(ifft2(e))
        if positiveOnly:
            e_img[e_img < 0.0] = 0.0
        e_img = e_img / np.sum(np.abs(e_img)) * I
        e = fft2(e_img)
        print 'iter #%d, total change: %f.' %\
            (i+1, np.sum(np.abs(e_img_old-e_img))/I)
        e_img_old = e_img
    return e_img
def frankotchellappa(dzdx, dzdy):
    rows, cols = dzdx.shape

    # The following sets up matrices specifying frequencies in the x and y
    # directions corresponding to the Fourier transforms of the gradient
    # data.  They range from -0.5 cycles/pixel to + 0.5 cycles/pixel.
    # The scaling of this is irrelevant as long as it represents a full
    # circle domain. This is functionally equivalent to any constant * pi
    pi_over_2 = np.pi / 2.0
    row_grid = np.linspace(-pi_over_2, pi_over_2, rows)
    col_grid = np.linspace(-pi_over_2, pi_over_2, cols)
    wy, wx = np.meshgrid(row_grid, col_grid, indexing='ij')

    # Quadrant shift to put zero frequency at the appropriate edge
    wx = ifftshift(wx)
    wy = ifftshift(wy)

    # Fourier transforms of gradients
    DZDX = fft2(dzdx)
    DZDY = fft2(dzdy)

    # Integrate in the frequency domain by phase shifting by pi/2 and
    # weighting the Fourier coefficients by their frequencies in x and y and
    # then dividing by the squared frequency
    denom = (wx ** 2 + wy ** 2)
    Z = (-1j * wx * DZDX - 1j * wy * DZDY) / denom
    Z = np.nan_to_num(Z)

    return np.real(ifft2(Z))
示例#12
0
def inverseFilter(img,fftsize):
    im = np.mean(img,2)/255.
    
    fftsize = 1024
    im_fft = fftpack.fft2(im, (fftsize, fftsize))
    
    #Complementary of a Gaussian filter
    SZ = 1024
    sigma = 0.25
    [xx,yy]=np.meshgrid(np.linspace(-4,4,SZ),np.linspace(-4,4,SZ))
    gaussian = np.exp(-0.5*(xx*xx+yy*yy)/(sigma*sigma))
    fil =1.-fftpack.fftshift(gaussian/np.max(gaussian))
    
    fil_fft =  fil
    
    im_fil_fft = im_fft * fil_fft
    
    im_fil = np.real(fftpack.ifft2(im_fil_fft))
    
    hs=np.floor(SZ/2.)
    #Careful with the crop. Because we work directly in the Fourier domain there is no padding.
    im_crop = im_fil[0:im.shape[0], 0:im.shape[1]]     
    F=fftpack.fft2(im_crop,(1024,1024))
    H=fil_fft
    tol= 1e-2
    I = F/H
    print np.min(I)
    I=np.where(np.abs(H)<tol,0,I)
    i_reconstructed = np.real(fftpack.ifft2(I))
    plt.imshow(i_reconstructed[:im.shape[0],:im.shape[1]],cmap="gray")
示例#13
0
 def getGeneralStatistics(self, hara=False, zern=False, tamura=False, only1D=None):
     generalStatistics = []
     if self.rows == 1 and self.columns == 1:
         for index in range(3):
             generalStatistics.append(self.image[0, 0, index])
         return generalStatistics
     if not only1D is None:
         im = only1D
         generalStatistics.extend(self._calculateStatistics(im, haralick=hara, zernike=zern))
         fourierTransform = np.abs(fftpack.fft2(im))  # fourierTransform
         generalStatistics.extend(self._calculateStatistics(fourierTransform))
         waveletTransform = pywt.dwt2(im, "sym5")[0]
         generalStatistics.extend(self._calculateStatistics(waveletTransform))
         waveletFourierTransform = pywt.dwt2(fourierTransform, "sym5")[0]
         generalStatistics.extend(self._calculateStatistics(waveletFourierTransform))
         if tamura:
             generalStatistics.extend(self.get3Dstatistics(tamura=True))
         return generalStatistics
     for index in range(3):
         im = self.image[:, :, index]
         generalStatistics.extend(self._calculateStatistics(im, haralick=hara, zernike=zern))
         fourierTransform = np.abs(fftpack.fft2(im))  # fourierTransform
         generalStatistics.extend(self._calculateStatistics(fourierTransform))
         waveletTransform = pywt.dwt2(im, "sym5")[0]
         generalStatistics.extend(self._calculateStatistics(waveletTransform))
         waveletFourierTransform = pywt.dwt2(fourierTransform, "sym5")[0]
         generalStatistics.extend(self._calculateStatistics(waveletFourierTransform))
     if tamura:
         generalStatistics.extend(self.get3Dstatistics(tamura=True))
     return generalStatistics
示例#14
0
文件: match.py 项目: enetland/spims
def correlate_layer(pattern_layer, source_layer):
    """
    Normalized Cross-Correlation for a single channel of an RGB image
    (or a greyscale image). Normalization is done as follows:
    normalized = (x - mean(x)) / std(x)

    pattern_layer - Two-dimensional ndarray, single channel of pattern image
    source_layer - Two-dimensional ndarray, single channel of source image

    """
    # http://bit.ly/WsRveH
    if pattern_layer.std() == 0:
        normalized_pattern = pattern_layer
    else:
        normalized_pattern = ((pattern_layer - np.mean(pattern_layer)) /
                              (np.std(pattern_layer) * pattern_layer.size))
    if source_layer.std() == 0:
        normalized_source = source_layer
    else:
        normalized_source = ((source_layer - np.mean(source_layer)) /
                             np.std(source_layer))

    #Take the fft of both Images, padding the pattern out with 0's
    # to be the same shape as the source
    pattern_fft = fftpack.fft2(normalized_pattern, source_layer.shape)
    source_fft = fftpack.fft2(normalized_source)

    # Perform the correlation in the frequency domain, which just the
    # inverse FFT of the pattern matrix's conjugate * the source matrix
    # http://en.wikipedia.org/wiki/Cross-correlation#Properties
    return fftpack.ifft2(pattern_fft.conjugate() * source_fft)
示例#15
0
    def solve(self, u, v, dx, dy):
        import numexpr as ne
        nx, ny = u.shape
        assert u.shape == tuple(self.shape)

        fu = fft2(u)
        fv = fft2(v)

        mpx = self.mpx
        mmx = self.mmx
        dpx = self.dpx
        dmx = self.dmx
        mpy = self.mpy
        mmy = self.mmy
        dpy = self.dpy
        dmy = self.dmy

        d = ne.evaluate("fu*mmy * dmx + fv * mmx * dmy")
        lapl = ne.evaluate("mpy  * mmy * dpx * dmx + mpx*mmx *dpy *dmy")
        lapl[0, 0] = 1.0

        p = d / lapl
        px = np.real(ifft2(mpy * dpx * p))
        py = np.real(ifft2(mpx * dpy * p))

        # self.p = np.real(ifft2(p))

        u -= px
        v -= py

        return px, py
示例#16
0
 def colorize_by_power(self, image):
     """
     Colorize the image mode-by-mode according to the power in each mode.  
     The top third of modes are colored red, the middle third green, and 
     the lower third blue.  For RGB images, a grayscale equivalent is 
     computed and colorized. 
     """
     print "colorizing....."
     if len(image.shape) == 3:
         power = fft2(np.sum(image, axis=2))**2
     elif len(image.shape) == 2:
         power = fft2(image)**2
     else:
         raise Exception("Invalid image shape: {}".foramt(image.shape))
     thirds = (power.max() - power.min())/3.0
     third_cut = power.min() + thirds
     twothird_cut = third_cut + thirds
     lower = power < third_cut
     upper = power > twothird_cut
     middle = ~(lower | upper)
     colorized = np.zeros((power.shape[0], power.shape[1], 3), 
                          dtype=np.uint8)
     for color, region in enumerate([upper, middle, lower]):
         new_channel = ifft2(np.where(region, power, 0.0))
         shifted = (new_channel - new_channel.min())
         scaled = 255.0*shifted/shifted.max()
         colorized[..., color] = ifft2(np.where(region, power, 0.0))
     return colorized
示例#17
0
    def shift_inner(arr, nx, ny, window=False, padding='reflect'):
        """
        Shifts an array by nx and ny respectively.

        """

        if ((nx % 1. == 0.) and (ny % 1. ==0)):
            return sp.roll(sp.roll(arr, int(ny), axis=0),
                           int(nx), axis=1)
        else:
            atype = arr.dtype
            if padding:
                x, y = arr.shape
                pwx, pwy = int(pow(2., np.ceil(np.log2(1.5*arr.shape[0])))), int(pow(2., np.ceil(np.log2(1.5*arr.shape[1]))))
                pwx2, pwy2 = (pwx-x)/2, (pwy-y)/2
                if pad=='zero':
                    arr = pad.with_constant(arr, pad_width=((pwx2, pwx2), (pwy2, pwy2)))
                else:
                    arr = pad.with_reflect(arr, pad_width=((pwx2, pwx2), (pwy2, pwy2)))
            phaseFactor = sp.exp(complex(0., -2.*sp.pi)*(ny*spf.fftfreq(arr.shape[0])[:, np.newaxis]+nx*spf.fftfreq(arr.shape[1])[np.newaxis, :]))
            if window:
                window = spf.fftshift(CXData._tukeywin(arr.shape[0], alpha=0.35))
                arr = spf.ifft2(spf.fft2(arr)*phaseFactor*window)
            else:
                arr = spf.ifft2(spf.fft2(arr)*phaseFactor)
            if padding:
                arr = arr[pwx/4:3*pwx/4, pwy/4:3*pwy/4]

        if atype == 'complex':
            return arr
        else:
            return np.real(arr)
示例#18
0
def tsvd_fft(B, PSF, center=None, tol=None,i=None):
    """TSVD_FFT Truncated SVD image deblurring using the FFT algorithm.

    X, tol = tsvd_fft(B, PSF, center, tol)

  Compute restoration using an FFT-based truncated spectral factorization.

  Input:
        B  Array containing blurred image.
      PSF  Array containing the point spread function.
  
  Optional Inputs:
   center  [row, col] = indices of center of PSF.
      tol  Regularization parameter (truncation tolerance).
             Default parameter chosen by generalized cross validation.

  Output:
        X  Array containing computed restoration.
      tol  Regularization parameter used to construct restoration."""
    #
    # compute the center of the PSF if it is not provided
    #
    if center is None:
        center = array(PSF.shape) / 2

    #
    # if PSF is smaller than B, pad it to the same size as B
    #
    if PSF.size < B.size:
        PSF = padarray(PSF, array(B.shape) - array(PSF.shape),
                       direction='post')
    
    #
    # Use the FFT to compute the eigenvalues of the BCCB blurring matrix.
    #
    S = fft2( circshift(PSF, 0-center) )
    #
    # If a regularization parameter is not given, use GCV to find one.
    #
    bhat = fft2(B)
    if i !=None:
        ev=abs(S.flatten())
        ev.sort()
        ev=ev[::-1]
        tol=ev[i] 
    elif tol is None:
        tol = gcv_tsvd(S.flatten('f'), bhat.flatten('f'))
	

    #
    # Compute the TSVD regularized solution.
    #
    
    idx = where(abs(S) >= tol)
    Sfilt = zeros(shape(bhat),'d')
    Sfilt[idx] = 1 / S[idx]
    X = real(ifft2(bhat * Sfilt))

    return X, sorted(S.flatten())[::-1]
示例#19
0
def tik_fft(B, PSF, center=None, alpha=None,sigma=None):
    """TIK_FFT Tikhonov image deblurring using the FFT algorithm.

    X, alpha = tik_fft(B, PSF, center, alpha)

    Compute restoration using an FFT-based Tikhonov filter, 
    with the identity matrix as the regularization operator.

    Input:
    B  Array containing blurred image.
    PSF  Array containing the point spread function.
  
    Optional Inputs:
    center  [row, col] = indices of center of PSF.
    alpha  Regularization parameter.
    Default parameter chosen by generalized cross validation.
    
    Output:
    X  Array containing computed restoration.
    alpha  Regularization parameter used to construct restoration.
    """
    #
    # compute the center of the PSF if it is not provided
    #
    if center is None:
        center = array(PSF.shape) / 2
    #
    # if PSF is smaller than B, pad it to the same size as B
    #
    if PSF.size < B.size:
        PSF = padarray(PSF, array(B.shape) - array(PSF.shape),
                       direction='post')
    #
    # Use the FFT to compute the eigenvalues of the BCCB blurring matrix.
    #
    S = fft2( circshift(PSF, 0-center) )
    s = S.flatten('f')
    bhat = fft2(B)
    bhat = bhat.flatten('f')
    #
    # If a regularization parameter is not given, use GCV to find one.
    #
##    if alpha is None:
    def tik_fft_obj(alpha,B,PSF,sigma):
        return abs(norm(tik_fft(B, PSF,alpha=abs(alpha)),2)-sigma) 
    
    if alpha is None:
        alpha = gcv_tik(s, bhat)
        print "alpha:", alpha,log10(alpha)

    #
    # Compute the Tikhonov regularized solution.
    #
    D = conj(s)*s + abs(alpha**2)
    bhat = conj(s) * bhat
    xhat = bhat / D
    xhat = reshape(asmatrix(xhat), shape(B), 'f')
    X = real(ifft2(xhat))
    return X
示例#20
0
def gauss_smooth(arr, w):
    """
    Smooths an input array by w pixels
    """
    alpha = w/2.3548
    pix = arr.shape[0]
    ker = sp.exp(-(alpha**-2.)*sp.hypot(*sp.ogrid[-pix/2:pix/2,-pix/2:pix/2])**2.)
    return sp.real(spf.fftshift(spf.ifft2( spf.fft2(arr)*spf.fft2(ker) )))
示例#21
0
def xcorr2(a2,b2):
    """ 2D cross correlation (unnormalized) """
    from scipy.fftpack import fftshift, fft2, ifft2
    from scipy import conj
    a2 = a2 - a2.mean()
    b2 = b2 - b2.mean()
    Nfft = (a2.shape[0] + b2.shape[0] - 1, a2.shape[1] + b2.shape[1] - 1)
    c = ifft2(fft2(a2,shape=Nfft) * fft2(nx.rot90(b2,2),shape=Nfft))
    #c = fftshift(ifft2(fft2(a2,shape=Nfft)*conj(fft2(b2,shape=Nfft))).real,axes=(0,1))
    return c.real
示例#22
0
	def FilterElectrons(self,sign, Psi):
 		'''
		Routine that uses the Fourier transform to filter positrons/electrons
		Options:
			sign=1   Leaves electrons
			sign=-1	 Leaves positrons
		'''
		print '  '
		print '  	Filter Electron routine '
		print '  '

		px = self.c*self.Px
		py = self.c*self.Py
		
		m = self.mass
		c= self.c

		energy = np.sqrt(  (m*c**2)**2 + px**2 + py**2 )

		EP_11 = 1. + sign*m*c**2/energy
		EP_12 = 0.
		EP_13 = 0.
		EP_14 = sign*(px - 1j*py)/energy
		
		EP_21 = 0.
		EP_22 = 1. + sign*m*c**2/energy
		EP_23 = sign*(px + 1j*py)/energy
		EP_24  = 0.

		EP_31 = 0.
		EP_32 = sign*(px - 1j*py)/energy
		EP_33 = 1. - sign*m*c**2/energy
		EP_34 = 0.

		EP_41 = sign*(px + 1j*py)/energy
		EP_42 = 0.
		EP_43 = 0.
		EP_44 = 1. - sign*m*c**2/energy	
		
		#Psi1, Psi2, Psi3, Psi4 = Psi

		psi1_fft = fftpack.fft2( Psi[0]  ) 
		psi2_fft = fftpack.fft2( Psi[1]  ) 
		psi3_fft = fftpack.fft2( Psi[2]  ) 
		psi4_fft = fftpack.fft2( Psi[3]  ) 		
		
		psi1_fft_electron = EP_11*psi1_fft + EP_12*psi2_fft + EP_13*psi3_fft + EP_14*psi4_fft
		psi2_fft_electron = EP_21*psi1_fft + EP_22*psi2_fft + EP_23*psi3_fft + EP_24*psi4_fft		
		psi3_fft_electron = EP_31*psi1_fft + EP_32*psi2_fft + EP_33*psi3_fft + EP_34*psi4_fft
		psi4_fft_electron = EP_41*psi1_fft + EP_42*psi2_fft + EP_43*psi3_fft + EP_44*psi4_fft
						
		return np.array([ fftpack.ifft2( psi1_fft_electron   ),
				  fftpack.ifft2( psi2_fft_electron   ),
	   			  fftpack.ifft2( psi3_fft_electron   ),
				  fftpack.ifft2( psi4_fft_electron   )  ])
示例#23
0
def powerspectrum(img, windowing=True):
    "Power spectrum of image"
    if windowing:
        window = np.hanning(img.shape[0])[:,np.newaxis]
        F = fftpack.fft2(np.dot(window,window.T)*img)
    else:
        F = fftpack.fft2(img)
    F = fftpack.fftshift(F)
    
    ps = np.abs(F)**2
    return ps      
示例#24
0
文件: twod.py 项目: natl/norotate
 def gravity(self):
   '''
   Evaluate the gravitational field, with a call to Bose.gravity()
   Gravitaional field is the convolution of the density and the log of distance
   '''
   den = abs(self.psi)**2.  #calculate the probability density
   
   #return the convolution, after multiplying by scaled gravity and 
   #correcting for grid scaling (due to 2 forward FFTs, and only one inverse
   return self.G*self.dx*self.dy*(ff.fftshift(ff.ifft2(ff.fft2(ff.fftshift(den)
     )*abs(ff.fft2(ff.fftshift(-self.log))))))
示例#25
0
文件: cmb.py 项目: amanzotti/PyCosmo
 def add_noise(self, temp):
   """
   Add per-pixel Gaussian random noise.
   """
   self.noise = random.normal(0,temp,[self.npix,self.npix])
   self.Fnoise = ft.fftshift(ft.fft2(self.noise))
   self.Txy = self.Txy + self.noise
   self.Fxy = ft.fftshift(ft.fft2(self.Txy))
   
   self.Clnoise = ((temp*self.mapsize_rad/self.npix)*self.Bl)**-2.e0
   self.Pknoise = np.interp(self.modk, self.k, self.Clnoise)
示例#26
0
	def _FilterElectrons(self,sign):
 		'''
		Routine that uses the Fourier transform to filter positrons/electrons
		Options:
			sign=1   Leaves electrons
			sign=-1	 Leaves positrons
		'''
		print '  '
		print '  	Filter Electron routine '
		print '  '
                min_Px = np.pi*self.X_gridDIM/(2*self.min_X)
		dPx = 2*np.abs(min_Px)/self.X_gridDIM
		px_Vector  = fftpack.fftshift ( np.linspace(min_Px, np.abs(min_Px) - dPx, self.X_gridDIM ))

		min_Py = np.pi*self.Y_gridDIM/(2*self.min_Y)
		dPy = 2*np.abs(min_Py)/self.Y_gridDIM
		py_Vector  = fftpack.fftshift ( np.linspace(min_Py, np.abs(min_Py) - dPy, self.Y_gridDIM ))


		px = px_Vector[np.newaxis,:]
		py = py_Vector[:,np.newaxis]


		sqrtp = sign*2*np.sqrt( self.mass*self.mass*self.c**4 + self.c*self.c*px*px + self.c*self.c*py*py )
		aa = sign*self.mass*self.c*self.c/sqrtp
		bb = sign*(px/sqrtp - 1j*py/sqrtp)
		cc = sign*(px/sqrtp + 1j*py/sqrtp)
	        
		ElectronProjector = np.matrix([ [0.5+aa , 0.  , 0.  , bb  ],
						[0. , 0.5+aa  , cc  , 0.  ],
						[0. , bb  , 0.5-aa  , 0.  ],
						[cc , 0.  , 0.  , 0.5-aa] ])

		psi1_fft = fftpack.fft2( self.Psi1_init   ) 
		psi2_fft = fftpack.fft2( self.Psi2_init   ) 
		psi3_fft = fftpack.fft2( self.Psi3_init   ) 
		psi4_fft = fftpack.fft2( self.Psi4_init   ) 		
		
		psi1_fft_electron = ElectronProjector[0,0]*psi1_fft + ElectronProjector[0,1]*psi2_fft +\
		ElectronProjector[0,2]*psi3_fft + ElectronProjector[0,3]*psi4_fft	

		psi2_fft_electron = ElectronProjector[1,0]*psi1_fft + ElectronProjector[1,1]*psi2_fft +\
		ElectronProjector[1,2]*psi3_fft + ElectronProjector[1,3]*psi4_fft

                psi3_fft_electron = ElectronProjector[2,0]*psi1_fft + ElectronProjector[2,1]*psi2_fft +\
		ElectronProjector[2,2]*psi3_fft + ElectronProjector[2,3]*psi4_fft	

                psi4_fft_electron = ElectronProjector[3,0]*psi1_fft + ElectronProjector[3,1]*psi2_fft +\
		ElectronProjector[3,2]*psi3_fft + ElectronProjector[3,3]*psi4_fft

                self.Psi1_init  = fftpack.ifft2( psi1_fft_electron   ) 
		self.Psi2_init  = fftpack.ifft2( psi2_fft_electron   ) 
		self.Psi3_init  = fftpack.ifft2( psi3_fft_electron   ) 
		self.Psi4_init  = fftpack.ifft2( psi4_fft_electron   ) 					
示例#27
0
def myconv2(A, B, zeropadding = False):
    # TO DO: zero padding to get rid of aliasing!
    if zeropadding:
        origdim = A.shape
        nextpow = pow(2, numpy.ceil(numpy.log(numpy.max(origdim))/numpy.log(2))+1)
        A = zeropad(A, nextpow.astype(int), nextpow.astype(int))
        B = zeropad(B, nextpow.astype(int), nextpow.astype(int))
    output = fftshift(ifft2( numpy.multiply(fft2(fftshift(A)), fft2(fftshift(B)) )))
    if zeropadding:
        output = output[nextpow/2 - origdim[0]/2: nextpow/2 + origdim[0]/2,nextpow/2 - origdim[1]/2: nextpow/2 + origdim[1]/2]
    return output
示例#28
0
文件: utils.py 项目: marcoviero/Utils
def alex_power_spec(map1, map2=None, deltal = 1, pixsize = 5.0):

  dims = np.shape(map1)
  if (map2 != None):
    spec = fftpack.fftshift(fftpack.fft2(map1)) * np.conj(fftpack.fftshift(fftpack.fft2(map2))) * (pi*pixsize/10800./60.)**2.0 * (dims[0]*dims[1])
  else:
    spec = np.abs(fftpack.fftshift(fftpack.fft2(map1))*(pi*pixsize/10800./60.))**2.0 * (dims[0]*dims[1])

  spec1d = radial_data(spec, annulus_width = deltal)

  return spec1d
示例#29
0
    def compute_pspec(self):
        '''
        Compute the 2D power spectrum.
        '''

        mvc_fft = fft2(self.centroid.astype("f8")) - \
            self.linewidth * fft2(self.moment0.astype("f8"))
        mvc_fft = fftshift(mvc_fft)

        self.ps2D = np.abs(mvc_fft) ** 2.

        return self
示例#30
0
文件: hosm.py 项目: mgoycoolea/hosm
def integration_and_analysis(zeta0, phi0, f_zeta_t, f_phi_t, M,
                             kxgrid, kygrid, ktgrid, dt, time, damping,
                             storage, wmax, wmin):
    '''
    Perform the 4th order Runge-Kutta integration scheme for
    surface and potential.

    zeta0: surface at time step n.
    phi0: potential at time step n.
    f_zeta_t, f_phi_t: functions with Euler eqs of M-order to be solved
    found with derive_euler_equation_functions(M).
    time: time in which the integration takes place
    damping: non-linear damping factor in Euler eqs.

    Return: surface and potential at time step n+1. 
    Other variables like the orders of phi can easily be returned!
    '''

    zeta = zeta0
    phi = phi0

    rk1_zeta, rk1_phi, phi_m = tderiv_surface_potential(zeta, phi, f_zeta_t, f_phi_t, M,
                                                 kxgrid, kygrid, ktgrid, time, damping,
                                                 return_phi_m = 1)
    zeta = zeta0 + rk1_zeta*dt/2
    phi = phi0 + rk1_phi*dt/2

    rk2_zeta, rk2_phi = tderiv_surface_potential(zeta, phi, f_zeta_t, f_phi_t, M,
                                                 kxgrid, kygrid, ktgrid, time + dt/2, damping)
    zeta = zeta0 + rk2_zeta*dt/2
    phi = phi0 + rk2_phi*dt/2

    rk3_zeta, rk3_phi = tderiv_surface_potential(zeta, phi, f_zeta_t, f_phi_t, M,
                                                 kxgrid, kygrid, ktgrid, time + dt/2, damping)
    zeta = zeta0 + rk3_zeta*dt
    phi = phi0 + rk3_phi*dt

    rk4_zeta, rk4_phi = tderiv_surface_potential(zeta, phi, f_zeta_t, f_phi_t, M,
                                                 kxgrid, kygrid, ktgrid, time + dt, damping)

    dzeta_dt = 1/6 * (rk1_zeta + rk4_zeta + 2*(rk2_zeta + rk3_zeta))
    dphi_dt = 1/6 * (rk1_phi + rk4_phi + 2*(rk2_phi + rk3_phi))

    
    kernel = monitor_conserved_quantities(phi0, zeta0, dzeta_dt, kxgrid, kygrid)
    print('Total Energy: ' + str(kernel['kin'] + kernel['poten']) + ' Total Mass:' +  str(kernel['mass']))

    zeta_next = np.real(ifft2(dealias(fft2(zeta0 + dt*dzeta_dt), M))) #We transform, dealias, then transform back as real. 
    phi_next = np.real(ifft2(dealias(fft2(phi0 + dt*dphi_dt), M)))

    storage, wmax, wmin = detect_rogue_waves(zeta0, zeta_next, wmax, wmin, sig_h, storage, time)

    return zeta_next, phi_next, phi_m, storage, wmax, wmin
示例#31
0
        img = thresh
    
    cv.imshow('Frame',gray)
        
    if cv.waitKey(1) == 27:
        break

cap.release()
cv.destroyAllWindows()

print(img.shape)


img = np.float32(img)
#template = np.float32(template)
A_ = fft.fft2(img)
shift_A = fft.fftshift(A_)

A_mag = 20*np.log(np.abs(shift_A)+1)


## mask ##
rows, cols = img.shape
crow, ccol = int(rows / 2), int(cols / 2)

mask = np.ones((rows, cols), np.uint8)
r = 80
center = [crow, ccol]
x, y = np.ogrid[:rows, :cols]
mask_area = (x - center[0]) ** 2 + (y - center[1]) ** 2 <= r*r
mask[mask_area] = 0
    A_k = np.abs(1./math.sqrt(k_x*k_x+k_y*k_y))
    phi_k = np.random.uniform(0.0,2.*math.pi)
    for j in range(ny):
        f[:,j] =  f[:,j] + A_k*np.cos(k_x*x+k_y*y[j]+phi_k) 
    k_x = -kx*2*math.pi/(xmax-xmin); k_y = ky*2*math.pi/(ymax-ymin)
    A_k = np.abs(1./math.sqrt(k_x*k_x+k_y*k_y))
    phi_k = np.random.uniform(0.0,2.*math.pi)
    for j in range(ny):
        f[:,j] =  f[:,j] + A_k*np.cos(k_x*x+k_y*y[j]+phi_k)#2-D field; must have both kxky>0 and kxky<0
#plt.figure()
#plt.contourf(f)
#plt.colorbar()
#plt.show()
print ( 'power in real space=', sum(sum(abs(f)*abs(f)))/(nx*ny) )

fft_f = fft2(f)
fft_fs = fftshift(fft_f) #arranges ks in correct order -N/2,..,0,..N/2
plt.figure()
kx = 2*math.pi*np.linspace(-nx/2,nx/2,nx); ky = 2*math.pi*np.linspace(-ny/2,ny/2,ny)
KX, KY = np.meshgrid(kx,ky,indexing='ij')
#plt.contourf(KX, KY, np.log10(np.abs(fft_fs)*np.abs(fft_fs)/(nx*nx*ny*ny)),40)
#plt.colorbar()
#plt.show()
print ( 'power in k-space=', sum(sum(abs(fft_f)*abs(fft_f)))/(nx*ny*nx*ny) )
kabs = np.zeros(nx*ny/2); Energy = np.zeros(nx*ny/2)
for l in range(nx):
    for m in range(int(ny/2)):
        kabs[m+l*ny/2] = math.sqrt( (l-nx/2)*(l-nx/2) +  m*m )
        Energy[m+l*ny/2] = 2.*np.abs(fft_fs[l,m+ny/2])*np.abs(fft_fs[l,m+ny/2])/(nx*ny*nx*ny)
plt.loglog(kabs,Energy,'o',kabs,1.e-2*kabs**-2)
plt.grid()
ax[0].imshow(contrasted1, cmap='gray')
ax[0].set(xlabel='', ylabel = '', title = 'Brightness 1')

ax[1].imshow(contrasted2, cmap='gray')
ax[1].set(xlabel='', ylabel = '', title = 'Brightness 2')

ax[2].imshow(contrasted3, cmap='gray')
ax[2].set(xlabel='', ylabel = '', title = 'Brightness 3')

plt.show()

'''
'''
Take the Fourier transform of each of the images
'''
fourier1 = fftpack.fft2(contrasted1)
fourier2 = fftpack.fft2(contrasted2)
fourier3 = fftpack.fft2(contrasted3)
'''
Plot the Fourier transform against the original image, and then the detected lines 

fig, ax = plt.subplots(ncols=3,nrows=2,figsize =(8,2.5))

ax[0][0].imshow(cropped1, cmap='gray')
ax[0][0].set(xlabel='', ylabel = '', title = 'Brightness 1')

ax[0][1].imshow(cropped2, cmap='gray')
ax[0][1].set(xlabel='', ylabel = '', title = 'Brightness 2')

ax[0][2].imshow(cropped3, cmap='gray')
ax[0][2].set(xlabel='', ylabel = '', title = 'Brightness 3')
print("p:", p)

#check if Katz compliant
if not mojette.isKatzCriterion(M, M, angles):
    print("Warning: Katz Criterion not met")

#create test image
#lena, mask = imageio.lena(N, p, True, np.uint32, True)
lena, mask = imageio.phantom(N, p, True, np.uint32, True)
#lena, mask = imageio.cameraman(N, p, True, np.uint32, True)

#-------------------------------
#k-space
#2D FFT
print("Creating kSpace")
fftLena = fftpack.fft2(lena)  #the '2' is important
fftLenaShifted = fftpack.fftshift(fftLena)
#power spectrum
powSpectLena = np.abs(fftLenaShifted)

#add noise to kSpace
noise = finite.noise(fftLenaShifted, SNR)
if addNoise:
    fftLenaShifted += noise

#Recover full image with noise
print("Actual noisy image")
reconLena = fftpack.ifft2(fftLenaShifted)  #the '2' is important
reconLena = np.abs(reconLena)
reconNoise = lena - reconLena
示例#35
0
def main():

    # Read the FITS file
    hdulist = fits.open('../Data/WISE_data.fit')
    image = hdulist[0]
    data = image.section[:][:]

    # Uncomment this block to plot the column density map
    # plt.title("WISE 12 um Survey \n (centered at (198,32) )")
    # plt.xlabel("Galactic longitude l (deg)")
    # plt.ylabel("Galactic latitude b (deg)")
    # plt.imshow(data,extent=(-2.35,2.35,-2.35,2.35))
    # plt.show()

    n = len(data[0])

    # Power spectrum calculation
    tba = np.average(data)
    thetab = np.zeros((n, n), float)
    for i in range(n):
        for j in range(n):
            thetab[i][j] = (data[i][j] - tba) * np.sin(i * np.pi / n) * np.sin(
                j * np.pi / n)

    # Autocorrelation and Fourier transform
    autocorr = correlate2d(thetab, thetab, mode='full') / n**4
    power2D = fftpack.fft2(autocorr)
    power2D = fftpack.fftshift(power2D)
    power2D = np.abs(power2D)

    n = len(power2D[0])

    # Create a grid of k values corresponding to the 2D power spectrum image
    kx = np.linspace(-1, 1, n)
    ky = np.linspace(-1, 1, n)
    kx = np.outer(np.ones(n), kx)
    ky = np.outer(ky, np.ones(n))
    k = np.zeros((n, n))
    for i in range(n):
        for j in range(n):
            k[i][j] = np.sqrt(kx[i][j]**2 + ky[i][j]**2)

    # Azimuthal averaging
    k1D, power1D = azimuthal_average.aave(k, power2D, int(n / 2))

    k1D = np.log10(k1D[1:])
    power1D = np.log10(power1D[1:])

    # Fit the log-log power spectrum to a linear function
    fit = stats.linregress(k1D[2:20], power1D[2:20])
    slope = fit[0]
    intercept = fit[1]
    error = fit[4]
    x = np.linspace(k1D[0], k1D[50], 1000)
    y = slope * x + intercept

    power1D = 10**(power1D)
    k1D = 10**(k1D)
    x = 10**(x)
    y = 10**(y)

    plt.loglog(k1D, power1D, label="Calculation")
    plt.loglog(x, y, label="Fit")
    plt.title("WISE Survey Power Spectrum \n beta=" + str('%.2f' % slope))
    plt.legend()
    plt.ylabel("P(k) (arbitrary units)")
    plt.xlabel("k (deg^-1)")
    plt.show()

    print("beta=" + str(slope))
    print("error=" + str(error))
示例#36
0
    G=np.fft.fftshift(G)
    return G


# lê imagem de entrada (f) em escala de cinza
#f = misc.face(gray=True)
f= cv2.imread('Lenna.png',0)
plt.figure()
cmap = 'gray'
plt.title('imagem original')
plt.imshow(f, cmap=cmap)
plt.colorbar()

#calculando a FFT 2D
F = fp.fft2(f)

#tratando a FFT para os gráficos
Fm = np.absolute(F)
Fm /= Fm.max()
Fm = fp.fftshift(Fm)
Fm = np.log(Fm)

#mostrando a FFT em escala logaritmica
plt.figure()
plt.title('FFT em escala log')
plt.imshow(Fm, cmap=cmap)
plt.colorbar()

# gerando a funcao gaussiana (o filtro)
sigma = 5
示例#37
0
    def simulate(self,
                 options,
                 crop=False,
                 zrange=(-100, 100),
                 zstep=10,
                 **kwargs):
        from multiprocessing import cpu_count, Pool

        results = dict()

        def save(key, _image, e_field=True):
            image = _image.copy()
            if e_field:
                image = np.square(image)
                image = np.real(image)
            results[key] = image

        pattern = self.slm_pattern(crop=False,
                                   **kwargs)  # do not crop in the process
        save("pattern", pattern, e_field=False)

        slm_field = np.exp(1j * pattern * np.pi)

        pre_mask = fftshift(fft2(ifftshift(slm_field)))
        save("pre_mask", pre_mask)

        self.mask.calibrate(self.field)
        post_mask = self.mask(pre_mask.copy())
        save("post_mask", post_mask)

        obj_field = fftshift(fft2(ifftshift(post_mask)))
        save("excitation_xz", obj_field)

        if "excitation_xy" in options:
            from tqdm import tqdm

            y = np.arange(*zrange, step=zstep)
            xy = np.zeros((self.field.shape[1], len(y)), dtype=obj_field.dtype)
            kz = self.field.kz()
            """
            # defocus term
            defocus = np.einsum("ji,k->jik", kz, y)
            defocus = np.exp(1j * defocus)

            # scan over z
            f = np.einsum("ji,jik->jik", post_mask, defocus)

            # back to real space
            f = ifftshift(f, axes=(0, 1))
            f = fft2(f, axes=(0, 1))
            f = fftshift(f, axes=(0, 1))

            # E field to intensity
            f = np.square(f)
            f = np.real(f)

            # select XY view
            xy = f.max(axis=0)
            """

            logger.info("iterating over Y axis")
            """
            for i, iy in tqdm(enumerate(y), total=len(y)):
                f = post_mask * np.exp(1j * kz * iy)
                f = fftshift(fft2(ifftshift(f)))

                f = np.square(f)
                f = np.real(f)

                xy[:, i] = f.max(axis=0)
            """
            with Pool(cpu_count()) as pool:
                func = partial(self._simulate_xy, post_mask=post_mask, kz=kz)
                xy = [
                    r for r in tqdm(pool.imap_unordered(func, y), total=len(y))
                ]
            xy.sort(key=lambda x: x[0])
            xy = np.vstack([i for _, i in xy])

            save("excitation_xy", xy.T)

        if crop:
            for key, image in results.items():
                results[key] = image[self.field._roi()]

        return results
示例#38
0
import scipy.misc 
import numpy, math 
import scipy.fftpack as fftim
from scipy.misc.pilutil import Image

# opening the image and converting it to grayscale
a = Image.open('../Figures/fft1.png').convert('L') 
# a is converted to an ndarray
b = scipy.misc.fromimage(a)
# performing FFT
c = fftim.fft2(b)
# shifting the Fourier frequency image  
d = fftim.fftshift(c) 

# intializing variables for convolution function
M = d.shape[0]
N = d.shape[1]
# H is defined and 
# values in H are initialized to 1
H = numpy.zeros((M,N)) 
center1 = M/2
center2 = N/2
d_0 = 30.0 # minimum cut-off radius
d_1 = 50.0 # maximum cut-off radius

# defining the convolution function for bandpass
for i in range(1,M):
    for j in range(1,N):
        r1 = (i-center1)**2+(j-center2)**2
        # euclidean distance from 
        # origin is computed
示例#39
0
def focal_ratio(img, xthreshold=None, ythreshold=0.001, wave=None, pixel=None, center=True, rebin=2,
                background_fit=True, background_fit_order=2, disp=False, ymin=1e-4):
    '''
    Compute the focal ratio from a PSF image using MTF = |OTF|

    Parameters
    ----------
    img : array
        PSF image

    threshold : float
        Threshold to determine the cutoff of the OTF. Default is 0.001

    wave : float
        Wavelength, in meters. Default is None

    pixel : float
        Pixel size, in meters. Default is None

    center : bool
        Recenter the PSF. Default value is True

    rebin : int
        Rebin factor for accurate recentering. Must be even. Default is 2

    background_fit : bool
        Fit and subtract the background from the OTF. Default is True

    background_fit_order : bool
        Order of the polynomial to fit the background in the OTF. Default is 2

    disp : bool
        Display a summary plot. Default is False

    ymin : float
        Minimal y value in the summary plot. Default is 1e-4

    Returns
    -------
    sampling : float
        Sampling of the PSF, in pixels

    fratio : float
        Focal ratio of the system. Computed only if wave and pixel are both provided.
    '''

    dim = img.shape[-1]

    if center:
        # image oversampling for subpixel accuracy on the image center
        # determination
        if rebin:
            if ((rebin % 2) != 0) and (rebin != 1):
                raise ValueError('rebin must be even')
        else:
            rebin = 1

        # oversampling
        tmp = fft.fftshift(fft.ifft2(fft.fftshift(img)))
        dim1 = dim * rebin
        tmp = np.pad(tmp, (dim1-dim)//2, mode='constant')
        img_big = fft.fftshift(fft.fft2(fft.fftshift(tmp))).real

        # find maximum
        imax = np.argmax(img_big)
        cy, cx = np.unravel_index(imax, img_big.shape)
        sx, sy = dim1 // 2 - cx, dim1 // 2 - cy

        # recenter
        img_big = imutils.shift(img_big, (sx, sy))

        # OTF
        otf = fft.fftshift(fft.ifft2(fft.fftshift(img_big)).real)
        otf = otf[(dim1-dim)//2:(dim1+dim)//2, (dim1-dim)//2:(dim1+dim)//2]
    else:
        # PSF already centered
        otf = fft.fftshift(np.abs(fft.ifft2(fft.fftshift(img))))

    if background_fit:
        # background subtraction using a linear fit on the first OTF
        # points
        otf_1d, r = imutils.profile(otf, ptype='mean', step=1, exact=False)

        dimfit = background_fit_order + 2
        u = np.arange(1, dimfit+1, dtype=np.float)
        v = otf_1d[1:dimfit+1]

        coeffs = np.polyfit(u, v, background_fit_order)
        poly   = np.poly1d(coeffs)
        fit    = poly(np.arange(dimfit+1))

        if fit[0] >= otf_1d[0]:
            print('Background lower than 0. No correction')
            otf_corr = otf / otf.max()
        else:
            otf_corr = otf.copy()
            otf_corr[dim//2, dim//2] = fit[0]
            otf_corr = otf_corr / fit[0]
    else:
        otf_corr = otf / otf.max()

    # first value of OTF below threshold
    otf_corr_1d, r = imutils.profile(otf_corr, ptype='mean', step=1, rmax=dim//2-1)
    
    if not xthreshold:
        xthreshold = r.max()
    
    rmax = r[(r <= xthreshold) & (otf_corr_1d >= ythreshold)].max()

    # sampling
    sampling = dim/rmax

    # theoretical OTF
    # pupil  = aperture.disc(512, 512, diameter=True, strict=True, cpix=True)
    # psf_th = np.abs(mft.mft(pupil, 512, dim, dim/sampling))**2
    # otf_th = fft.fftshift(np.abs(fft.ifft2(fft.fftshift(psf_th)))).real
    # otf_th = otf_th / otf_th.max()
    # otf_th_1d = otf_th[dim//2, dim//2:]
    # otf_th_r  = np.arange(dim//2)
    
    # compute uncertainty related to image sampling
    sampling_min = dim / (rmax + 1)
    sampling_max = dim / (rmax - 1)
    print(f'Sampling: {sampling:.2f} ({sampling_min:.2f}-{sampling_max:.2f})')
    
    # focal ratio
    fratio = None
    if wave is not None and pixel is not None:
        fratio = sampling * pixel / wave

        # compute uncertainty related to image sampling
        fratio_min = sampling_min * pixel / wave
        fratio_max = sampling_max * pixel / wave

        print(f'F ratio: {fratio:.2f} ({fratio_min:.2f}-{fratio_max:.2f})')

    # display result
    if disp:
        otf = otf / otf.max()
        otf_1d, r_otf = imutils.profile(otf, ptype='mean', step=1, rmax=dim//2-1)
        otf_corr_1d, r = imutils.profile(otf_corr, ptype='mean', step=1, rmax=dim//2-1)

        plt.figure('OTF', figsize=(8, 8))
        plt.clf()
        plt.imshow(otf_corr, norm=colors.LogNorm(vmin=1e-4, vmax=1))
        plt.title('OTF')
        plt.tight_layout()
        
        plt.figure('F ratio estimation', figsize=(12, 9))
        plt.clf()
        
        plt.semilogy(r_otf, otf_1d, lw=2, marker='+', label='MTF')
        plt.semilogy(r_otf, otf_corr_1d, lw=2, linestyle='--', marker='+', label='MTF (corrected)')
        # plt.semilogy(otf_th_r, otf_th_1d, lw=2, linestyle='-', color='k', label='MTF (theoretical)')

        plt.axhline(ythreshold, linestyle='--', color='r', lw=1)
        plt.axvline(rmax, linestyle='--', color='r', lw=1)

        if fratio:
            plt.title(f'Sampling = {sampling:.2f} pix / ($\lambda/D$) - F ratio = {fratio:.2f}')
        else:
            plt.title(f'Sampling = {sampling:.2f} pix / ($\lambda/D$)')

        plt.xlim(0, xthreshold)
        plt.xlabel('Cutoff pixel')
        plt.gca().xaxis.set_major_locator(ticker.MultipleLocator(5))
        plt.gca().xaxis.set_minor_locator(ticker.MultipleLocator(1))

        if fratio:
            plt.gca().spines.top.set_visible(False)
            plt.gca().xaxis.set_ticks_position('bottom')

            secax = plt.gca().secondary_xaxis('top')
            secax.set_xlim(plt.xlim())
            secax.xaxis.set_major_locator(ticker.MultipleLocator(1))
            secax.xaxis.set_minor_locator(ticker.MultipleLocator(1))
            secax.xaxis.set_major_formatter(lambda x, pos: f'{dim / x * pixel / wave:.2f}')

            secax.tick_params(axis='x', bottom=False, top=True, labelbottom=False, labeltop=True, rotation=75)
        
        plt.ylim(ymin, 1)
        plt.ylabel('MTF')        
        
        plt.legend(loc='center left')
        plt.tight_layout()
                

    return sampling, fratio
示例#40
0
@author: IIST
"""
import numpy as np
import math
from PIL import Image
from scipy import fftpack as fftp
import imageio
import cmath
from matplotlib import pyplot as plt

img = Image.open(
    'C:/Users/IIST/Downloads/Ragja/7_SC18M003_Ragja_IP2018/Book.tif')
img.load()
data = np.asarray(img, dtype="float64")

image_fft = fftp.fft2(data)
a = 0.1
k = 0.00025
T = 1
H = np.zeros((688, 688), dtype="complex")

for u in range(1, 689):
    for v in range(1, 689):
        den = u**2 + v**2
        exponent = k * (den**(5 / 6))
        H[u - 1, v - 1] = math.exp(-exponent)

final_image2 = image_fft * H
image2 = np.fft.ifft2(final_image2)
imgfinal = Image.fromarray((image2).astype('uint'))
#imgfinal.save('equalized_image.png')
示例#41
0
def fftclean(cube_array,
             cut=np.array([[443, 449, 436, 441], [458, 462, 465, 470],
                           [440, 445, 451, 456], [461, 466, 451, 455],
                           [428, 430, 452, 454], [475, 478, 452, 454],
                           [489, 495, 452, 458], [411, 418, 449, 453]]),
             zoom=[410, 460, 410, 460],
             plot=1,
             n=1,
             m=1,
             taper=1):
    '''
    Allows for simple FFT cleaning by removing two boxes around the FFT image.
    Remember to use taper_cube() before running!
    
    INPUT:
        cube_array  : name of 3D numpy array that needs to be tapered. Remember to use taper_cube!
        cut1        : first box to be removed   Default: [417,430, 410,421]
        cut2        : secpnd box to be removed  Default: [430,443, 438,450]
        zoom        : Zoom into central spike   Default: [410,460,410,460]
        plot        : Show diagnostic plot      Default: True
    
    OUTPUT:
        imput array after filtering and diagnostic plot if plot=1.
    
    AUTHOR: Alex
    
    '''
    dim = cube_array.shape[-1]
    frame_median = np.tile(np.median(cube_array, axis=[2, 1]), (dim, dim, 1)).T

    red_cube_array, frame_median = taper_cube(cube_array, taper=taper)

    #make image for mask.
    im_fft = (fftpack.fft2(red_cube_array))
    if plot:
        #take power to visualize what we are looking at. We only use this for images.

        im_po = fftpack.fftshift((np.conjugate(im_fft) * im_fft).real)

        im_mean = np.mean(im_po)
        im_std = np.std(im_po)

    im_mean_im = np.median(red_cube_array[0])

    im_std_im = np.std(red_cube_array)

    mask = np.empty_like(red_cube_array[0]) * 0 + 1
    for k in range((cut.shape[0])):
        mask[cut[k, 0]:cut[k, 1], cut[k, 2]:cut[k, 3]] = 0

    if plot:
        im_po_mask = im_po * mask

    #use FFT and not power to apply mask and get clean image
    im_fft = fftpack.fftshift(im_fft)
    im_fft_mask = im_fft * mask
    im_mask = fftpack.ifft2(fftpack.ifftshift(im_fft_mask)).real + frame_median

    if plot:
        plt.subplot(221)
        plt.imshow(red_cube_array[0],
                   vmin=im_mean_im - n * im_std_im,
                   vmax=im_mean_im + n * im_std_im)
        plt.colorbar()
        plt.subplot(222)
        plt.imshow(im_po[0],
                   vmin=im_mean - m * im_std,
                   vmax=im_mean + m * im_std)
        #plt.xlim(zoom[0],zoom[1])
        #plt.ylim(zoom[2],zoom[3])
        plt.colorbar()
        plt.subplot(223)
        plt.imshow(im_mask[0],
                   vmin=frame_median[0, 0, 0] - n * im_std_im,
                   vmax=frame_median[0, 0, 0] + n * im_std_im)
        plt.colorbar()
        plt.subplot(224)
        plt.imshow(im_po_mask[0],
                   vmin=im_mean - m * im_std,
                   vmax=im_mean + m * im_std)
        #plt.xlim(zoom[0],zoom[1])
        #plt.ylim(zoom[2],zoom[3])
        plt.colorbar()
        plt.show()

    return im_mask
示例#42
0
plt.imshow(triangulos, cmap='Greys_r')

plt.savefig("imagenes.pdf")

#EL SIGUIENTE METODO ES PARA PASAR LA IMAGEN DE 3D A 2D FUE SACADO DEL BLOG :https://stackoverflow.com/questions/12201577/how-can-i-convert-an-rgb-image-into-grayscale-in-python


def rgb2gray(rgb):

    r, g, b = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2]
    gray = 0.2989 * r + 0.5870 * g + 0.1140 * b

    return gray


transformada_barcelona = fftpack.fft2(rgb2gray(barcelona))
transformada_paris = fftpack.fft2(rgb2gray(paris))
transformada_fractal = fftpack.fft2(rgb2gray(fractal))
transformada_triangulos = fftpack.fft2(rgb2gray(triangulos))

plt.figure()

plt.subplot(221)
plt.imshow(np.log10(np.abs(transformada_barcelona**2)))
plt.subplot(222)
plt.imshow(np.log10(np.abs(transformada_paris**2)))

plt.subplot(223)
plt.imshow(np.log10(np.abs(transformada_fractal**2)))

plt.subplot(224)
	def real_fft2d(self, image, *args, **kwargs):
		padshape = numpy.asarray(image.shape)*1
		padimage = apImage.frame_constant(image, padshape, image.mean())
		fft = fftpack.fft2(padimage, *args, **kwargs)
		return fft
示例#44
0
def psd2d(sigs,
          t,
          x,
          dt=None,
          dx=None,
          nfft=256,
          noverlap=None,
          nensemble=1,
          istart=0,
          tstart=None,
          window='hanning',
          detrend='constant'):
    """
    Estimate 2D cross power spectral density using Welch's method.
    ----------
    sigs : 2D-array
        Time series of measurement values
    t : 1D-array
        Time for sigs
    x : 1D-array
        Locations for sigs
    dt : float, optional
        Sampling time of the `sigs` time series in units of sec. Defaults
        to None.
    dx : float, optional
        Sampling space of the `sigs` time series in units of m. Defaults
        to None.
    nfft : int, optional
        Length of each segment and  Length of the FFT used. 
    noverlap : int, optional
        Number of points to overlap between segments. If None,
        ``noverlap = nperseg // 8``.  Defaults to None.
    nensemble: int, optional
        Number of ensembles  Defaults to 1.
    istart: int, optional
        Start index in the specified axis of sigs. Defaults to 0.
    tstart: float, optional
        Start time of sigs. If None, t[istart] is used. Defaults to None.
    window : str or tuple or array_like, optional
        Desired window to use. See `get_window` for a list of windows and
        required parameters. Defaults to 'hanning'.
    detrend : str or function or False, optional
        Specifies how to detrend each segment. If `detrend` is a string,
        it is passed as the ``type`` argument to `detrend`.  If it is a
        function, it takes a segment and returns a detrended segment.
        If `detrend` is False, no detrending is done.  Defaults to 'constant'.
    Returns
    -------
    ft : ndarray
        Array of sample frequencies in time domain.
    fx : ndarray
        Array of sample frequencies in space domain.
    Ptx : ndarray (2D)
        Power spectral density or power spectrum of x. Pxx(f, tave).
    See Also
    --------
    Notes
    -----
        see welch
    """

    nt = len(t)
    nx = len(x)
    if dt is None:
        dt = (t[-1] - t[0]) / (nt - 1)

    if dx is None:
        dx = (x[-1] - x[0]) / (nx - 1)

    if len(t) < nfft:
        warnings.warn(
            'nfft = {0}, is greater than len(t) = {1}, using nfft = {2}'.
            format(nfft, nt, nt))
        nfft = len(t)

    if tstart is not None:
        indx = np.where(t >= tstart)[0]
        istart = indx[0]

    if noverlap is None:
        noverlap = nfft // 2
    elif noverlap >= nfft:
        raise ValueError('noverlap must be less than nfft.')

    step = nfft - noverlap
    iend = step * (nensemble - 1) + nfft + istart
    if iend > nt:
        nnew = (nt - nfft - istart) / step + 1
        warnings.warn(
            'nensemble = {0} exceed boundary, using nensemble = {1}'.format(
                nt, nnew))
        nfft = nnew

    Ptx = np.zeros((nfft, nx))

    if sigs.size == 0:
        return np.empty(nfreq), tave, Pxx

    win_t = dsp.get_window(window, nfft)
    scale_t = dt / (win_t * win_t).sum()

    win_x = dsp.get_window(window, nx)
    scale_x = dx / (win_x * win_x).sum()
    scale = scale_t * scale_x

    if not detrend:
        detrend_func = lambda seg: seg
    elif not hasattr(detrend, '__call__'):
        detrend_func = lambda seg: dsp.detrend(seg, type=detrend)
    else:
        detrend_func = detrend

    work = np.empty((nfft, nx), dtype=complex)
    spc = np.zeros((nfft, nx), dtype=complex)
    for ne in range(nensemble):
        i0 = istart + noverlap * ne
        i1 = i0 + nfft
        for j in range(nx):
            work[:, j] = win_x[j] * win_t * detrend_func(sigs[i0:i1, j])
        spc = fft.fft2(work)
        Ptx = Ptx + (spc * spc.conj()).real
    Ptx = scale * Ptx / nensemble
    Ptx = fft.fftshift(Ptx)
    ft = fft.fftfreq(nfft, dt)
    ft = fft.fftshift(ft)
    fx = fft.fftfreq(nx, dx)
    fx = fft.fftshift(fx)

    return ft, fx, Ptx
示例#45
0
from scipy import fftpack
#import pyfits
import numpy as np
import pylab as py
import radialProfile
 
image = Image.open('agujero.jpg')
 
# Take the fourier transform of the image.
F1 = fftpack.fft2(image)
 
# Now shift the quadrants around so that low spatial frequencies are in
# the center of the 2D fourier transformed image.
F2 = fftpack.fftshift( F1 )
 
# Calculate a 2D power spectrum
psd2D = np.abs( F2 )**2
 
# Calculate the azimuthally averaged 1D power spectrum
psd1D = radialProfile.azimuthalAverage(psd2D)
 
# Now plot up both
py.figure(1)
py.clf()
py.imshow( np.log10( image ), cmap=py.cm.Greys)
 
py.figure(2)
py.clf()
py.imshow( np.log10( psf2D ))
 
py.figure(3)
示例#46
0
def power_spectrum(inputTestName, outputTestName, cb=True, plot=True):
    """ cb : True if the spectrum is computed on the whole chla_final image
        cb : False if teh sppectrum is computed only on the restricted area contianing 
             the inpainted image.
        plot= True enables the visualization of 20 images sampled randomly.
        plot = False disables the visualization of 20 images sampled randomly. """
    #outputTestName = '../data/cloud/DatasetNN_cloud.nc'
    #inputTestName = '../data/cloud/BaseTest_cloud.nc'
    PSD2D = []
    PSD1D = []
    if cb == True:
        outputTest = xr.open_dataset(outputTestName)
        chla_final = outputTest.yfinal.values.squeeze()
        for i in range(chla_final.shape[0]):
            chlaF = chla_final[i, :, :]
            # CALCUL DU SPECTRE DE PUISSANCE
            # Take the fourier transform of the image.
            F1 = fftpack.fft2(chlaF)
            # Now shift the quadrants around so that low spatial frequencies are in
            # the center of the 2D fourier transformed image.
            F2 = fftpack.fftshift(F1)
            # Calculate a 2D power spectrum
            psd2D = np.abs(F2)**2
            PSD2D.append(
                psd2D.tolist())  # array contenant les a 2D power spectrum
            # Calculate the azimuthally averaged 1D power spectrum
            psd1D = azimuthalAverage(psd2D)
            PSD1D.append(psd1D.tolist())
        if plot == True:
            # Visualisation de 20 images tirées aléatoirement
            nim = 20
            idx = np.random.randint(0, chla_final.shape[0], nim)
            for i, ind in enumerate(idx):
                fig, ax = plt.subplots(ncols=3)
                ax[0].imshow(np.log10(chla_final[ind, :, :]))
                ax[1].imshow(np.log10(np.array(PSD2D[ind])))
                ax[2].plot(PSD1D[ind])

    elif cb == False:
        CHLAFC, chla_finalV = inpainted_region(inputTestName, outputTestName)
        for i in range(chla_finalV.shape[0]):
            chlaFC = np.array(CHLAFC[i])
            # CALCUL DU SPECTRE DE PUISSANCE
            # Take the fourier transform of the image.
            F1 = fftpack.fft2(chlaFC)
            # Now shift the quadrants around so that low spatial frequencies are in
            # the center of the 2D fourier transformed image.
            F2 = fftpack.fftshift(F1)
            # Calculate a 2D power spectrum
            psd2D = np.abs(F2)**2
            PSD2D.append(
                psd2D.tolist())  # array contenant les a 2D power spectrum
            # Calculate the azimuthally averaged 1D power spectrum
            psd1D = azimuthalAverage(psd2D)
            PSD1D.append(psd1D.tolist())
        if plot == True:
            # Visualisation de 20 images tirées aléatoirement
            nim = 20
            ii = np.random.randint(0, chla_finalV.shape[0], nim)
            for i, ind in enumerate(ii):
                fig, ax = plt.subplots(ncols=3)
                ax[0].imshow(np.array(CHLAFC[ind]))
                ax[1].imshow(np.log10(np.array(PSD2D[ind])))
                ax[2].plot(PSD1D[ind])

    else:
        print("cb est un booléen ! ")
    return PSD2D, PSD1D
示例#47
0
 def fourier(self):
     F1 = fftpack.fft2(self.image)
     F2 = fftpack.fftshift(F1)
     return F2
示例#48
0
def fft_denoise(file_name):
    """
    ======================
    Image denoising by FFT
    ======================
    Denoise an image (:download:`../../../../data/moonlanding.png`) by
    implementing a blur with an FFT.

    Implements, via FFT, the following convolution:

    .. math::

        f_1(t) = \int dt'\, K(t-t') f_0(t')

    .. math::

        \tilde{f}_1(\omega) = \tilde{K}(\omega) \tilde{f}_0(\omega)

    """
    ############################################################
    # Read and plot the image
    ############################################################
    im = plt.imread(file_name).astype(float)
    im = im[:, :, 0]
    plt.figure()
    plt.imshow(im, plt.cm.gray)
    plt.title('Original image')
    ############################################################
    # Compute the 2d FFT of the input image
    ############################################################
    im_fft = fftpack.fft2(im)

    # Show the results
    def plot_spectrum(im_fft):
        from matplotlib.colors import LogNorm
        # A logarithmic colormap
        plt.imshow(np.abs(im_fft), norm=LogNorm(vmin=5))
        plt.colorbar()

    plt.figure()
    plot_spectrum(im_fft)
    plt.title('Fourier transform')
    ############################################################
    # Filter in FFT
    ############################################################
    # In the lines following, we'll make a copy of the original spectrum and
    # truncate coefficients.

    # Define the fraction of coefficients (in each direction) we keep
    keep_fraction = 0.1
    # Call ff a copy of the original transform. Numpy arrays have a copy
    # method for this purpose.
    im_fft2 = im_fft.copy()
    # Set r and c to be the number of rows and columns of the array.
    r, c = im_fft2.shape
    # Set to zero all rows with indices between r*keep_fraction and
    # r*(1-keep_fraction):
    im_fft2[int(r * keep_fraction):int(r * (1 - keep_fraction))] = 0
    # Similarly with the columns:
    im_fft2[:, int(c * keep_fraction):int(c * (1 - keep_fraction))] = 0
    plt.figure()
    plot_spectrum(im_fft2)
    plt.title('Filtered Spectrum')
    ############################################################
    # Reconstruct the final image
    ############################################################
    # Reconstruct the denoised image from the filtered spectrum, keep only the
    # real part for display.
    im_new = fftpack.ifft2(im_fft2).real
    plt.figure()
    plt.imshow(im_new, plt.cm.gray)
    plt.title('Reconstructed Image')
    ############################################################
    # Easier and better: :func:`scipy.ndimage.gaussian_filter`
    ############################################################
    #
    # Implementing filtering directly with FFTs is tricky and time consuming.
    # We can use the Gaussian filter from :mod:`scipy.ndimage`
    from scipy import ndimage
    im_blur = ndimage.gaussian_filter(im, 4)
    plt.figure()
    plt.imshow(im_blur, plt.cm.gray)
    plt.title('Blurred image')
    plt.show()
示例#49
0
img_1 = cv2.imread('Fig0441(a)(characters_test_pattern).tif', 0)

figure()
plt.imshow(img_1, cmap=plt.get_cmap('gray'), vmin=0, vmax=255)
title('Original Image')
show()

height = np.size(img_1, 0)  #generate height and
width = np.size(img_1, 1)  #width to loop over them
img = np.zeros((height * 2, width * 2))
img_2 = img.copy()
img_2[:img_1.shape[0], :img_1.shape[1]] -= img_1

a = scipy.misc.toimage(img_2).convert('L')
b = scipy.misc.fromimage(a)
c = fftim.fft2(b)
d = fftim.fftshift(c)

magnitude_spectrum = 20 * np.log(np.abs(d))
cv2.circle(magnitude_spectrum, (688, 688), 10, (0, 0, 255), 5)
cv2.circle(magnitude_spectrum, (688, 688), 15, (0, 0, 255), 5)
cv2.circle(magnitude_spectrum, (688, 688), 60, (0, 0, 255), 5)
cv2.circle(magnitude_spectrum, (688, 688), 160, (0, 0, 255), 5)
cv2.circle(magnitude_spectrum, (688, 688), 460, (0, 0, 255), 5)

font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(magnitude_spectrum, '460', (788, 200), font, 2, (0, 0, 255), 5,
            cv2.LINE_AA)
cv2.putText(magnitude_spectrum, '160', (750, 550), font, 2, (0, 0, 255), 5,
            cv2.LINE_AA)
cv2.putText(magnitude_spectrum, '60', (750, 650), font, 2, (0, 0, 255), 5,
示例#50
0
#face sources and vertex sources
#By picking sources we may pick vortex (curly face) or charge (divergency vertex) sources
sourcef = np.zeros((N,N))
sourcef[pos(L/2 + .1),pos(L/2)] = -1/dx**2
#sourcef[pos(L/2 - .1),pos(L/2)] = 1/dx**2

sourcev = np.zeros((N,N))

#make charges
'''
sourcev = sourcef
sourcef = np.zeros((N,N))
'''

# face and vertex potentials
phikf = fft2(sourcef) / L2
phikf[0,:]=0
phikf[:,0]=0

phikv = fft2(sourcev) / L2
phikv[0,:]=0
phikv[:,0]=0

phiv= np.real(ifft2(phikv))
phif= np.real(ifft2(phikf))

# A = curl phif + grad phiv is a 2D helmholtz decomposition
# curl uses backards difference, grad uses forward difference. It's how it works out
# curl: face -> edge is the transpose of curl: edge -> face and takes backwards to forwards difference
Akx = Dby * phikf + Dfx * phikv
Aky = - Dbx * phikf + Dfy * phikv
cC = imCShape[1]

if len(imCShape) >2:
    imC = imC[:,:,1]


plt.figure()
plt.imshow(im, plt.cm.gray)
plt.title('Original image')


############################################################
# Compute the 2d FFT of the input image
############################################################
from scipy import fftpack
im_fft = fftpack.fft2(im)
imC_fft = fftpack.fft2(imC)

# Show the results

def plot_spectrum(im_fft):
    from matplotlib.colors import LogNorm
    # A logarithmic colormap
    plt.imshow(np.abs(im_fft), norm=LogNorm(vmin=5))
    plt.colorbar()

plt.figure()
plot_spectrum(im_fft)
plt.title('Fourier transform')

############################################################
示例#52
0
mask = pfft.fftshift(convert_locations_to_mask(samples, SOS.shape))
image = pysap.Image(data=np.abs(SOS))
image.show()


#############################################################################
# Generate the kspace
# -------------------
#
# From the 2D brain slice and the acquistion mask, we generate the acquisition
# measurments, the observed kspace.
# We then reconstruct the zero order solution.

# Generate the subsampled kspace
Sl = np.asarray([Smaps[l] * SOS for l in range(Smaps.shape[0])])
kspace_data = np.asarray([mask * pfft.fft2(Sl[l]) for l in
                          range(Sl.shape[0])])
mask = pysap.Image(data=pfft.fftshift(mask))
mask.show()


# Get the locations of the kspace samples
kspace_loc = convert_mask_to_locations(pfft.fftshift(mask.data))


#############################################################################
# FISTA optimization
# ------------------
#
# We now want to refine the zero order solution using a FISTA optimization.
# Here no cost function is set, and the optimization will reach the
feliz = plt.imread("cara_03_grisesMF.png")

print(np.shape(feliz))


def LowP(imagen, corte=.1):
    r, M = np.shape(imagen)
    if (M % 2 != 0):
        M += 1
    h = np.sin(2 * np.pi * corte * (imagen - (M / 2))) / (imagen - (M / 2))
    w = 0.54 - 0.46 * np.cos(2 * np.pi * imagen / M)
    im = w * h
    return im


Fseria = fft2(seria).real
Fseria = np.log10(abs(Fseria))
print(np.shape(Fseria))
print(Fseria)

filtro = LowP(Fseria)
IFseria = ifft2(filtro).real

plt.figure()
plt.subplot(2, 2, 1)
plt.imshow(seria)
plt.subplot(2, 2, 2)
plt.imshow(filtro)
plt.subplot(2, 2, 3)
plt.imshow(IFseria)
plt.subplot(2, 2, 4)
    def GiveSpectralIndexMap(self,
                             GaussPars=[(1, 1, 0)],
                             ResidCube=None,
                             GiveComponents=False,
                             ChannelWeights=None):

        # convert to radians
        ex, ey, pa = GaussPars
        ex *= np.pi / 180 / np.sqrt(2) / 2
        ey *= np.pi / 180 / np.sqrt(2) / 2
        # pa -= 180.0
        pa *= np.pi / 180 / np.sqrt(2) / 2

        # get in terms of number of cells
        CellSizeRad = self.GD['Image']['Cell'] * np.pi / 648000
        # ex /= self.GD['Image']['Cell'] * np.pi / 648000
        # ey /= self.GD['Image']['Cell'] * np.pi / 648000

        # get Gaussian kernel
        GaussKern = ModFFTW.GiveGauss(self.Npix,
                                      CellSizeRad=CellSizeRad,
                                      GaussPars=(ex, ey, pa),
                                      parallel=False)

        # import matplotlib.pyplot as plt
        # plt.imshow(GaussKern)
        # plt.show()

        # normalise
        # GaussKern /= np.sum(GaussKern.flatten())
        # take FT
        Fs = np.fft.fftshift
        iFs = np.fft.ifftshift

        # evaluate model
        ModelImage = self.GiveModelImage(self.GridFreqs)

        # pad GausKern and take FT
        GaussKern = np.pad(GaussKern, self.Npad, mode='constant')
        FTshape, _ = GaussKern.shape
        from scipy import fftpack as FT
        GaussKernhat = FT.fft2(iFs(GaussKern))

        # pad and FT of ModelImage
        ModelImagehat = np.zeros((self.Nchan, FTshape, FTshape),
                                 dtype=np.complex128)
        ConvModelImage = np.zeros((self.Nchan, self.Npix, self.Npix),
                                  dtype=np.float64)
        I = slice(self.Npad, -self.Npad)
        for i in xrange(self.Nchan):
            tmp_array = np.pad(ModelImage[i, 0], self.Npad, mode='constant')
            ModelImagehat[i] = FT.fft2(iFs(tmp_array)) * GaussKernhat
            ConvModelImage[i] = Fs(FT.ifft2(ModelImagehat[i]))[I, I].real

        if ResidCube is not None:
            ConvModelImage += ResidCube.squeeze()
            RMS = np.std(ResidCube.flatten())
            Threshold = self.GD["SPIMaps"]["AlphaThreshold"] * RMS
        else:
            RMS = np.abs(np.min(ModelImage.flatten())
                         )  # base cutoff on smallest value in model
            Threshold = self.GD["SPIMaps"]["AlphaThreshold"] * RMS

        # get minimum along any freq axis
        MinImage = np.amin(ConvModelImage, axis=0)
        MaskIndices = np.argwhere(MinImage > Threshold)
        FitCube = ConvModelImage[:, MaskIndices[:, 0], MaskIndices[:, 1]]

        if ChannelWeights is None:
            weights = np.ones(self.Nchan, dtype=np.float32)
        else:
            weights = ChannelWeights.astype(np.float32)
            if ChannelWeights.size != self.Nchan:
                import warnings
                warnings.warn(
                    "The provided channel weights are of incorrect length. Ignoring weights.",
                    RuntimeWarning)
                weights = np.ones(self.Nchan, dtype=np.float32)

        try:
            import traceback
            from africanus.model.spi.dask import fit_spi_components
            NCPU = self.GD["Parallel"]["NCPU"]
            if NCPU:
                from multiprocessing.pool import ThreadPool
                import dask

                dask.config.set(pool=ThreadPool(NCPU))
            else:
                import multiprocessing
                NCPU = multiprocessing.cpu_count()

            import dask.array as da
            _, ncomps = FitCube.shape
            FitCubeDask = da.from_array(FitCube.T.astype(np.float64),
                                        chunks=(ncomps // NCPU, self.Nchan))
            weightsDask = da.from_array(weights.astype(np.float64),
                                        chunks=(self.Nchan))
            freqsDask = da.from_array(np.array(self.GridFreqs).astype(
                np.float64),
                                      chunks=(self.Nchan))

            alpha, varalpha, Iref, varIref = fit_spi_components(
                FitCubeDask,
                weightsDask,
                freqsDask,
                self.RefFreq,
                dtype=np.float64).compute()
        except Exception as e:
            traceback_str = traceback.format_exc(e)
            print>>log, "Warning - Failed at importing africanus spi fitter. This could be an issue with the dask " \
                        "version. Falling back to (slow) scipy version"
            print >> log, "Original traceback - ", traceback_str
            alpha, varalpha, Iref, varIref = self.FreqMachine.FitSPIComponents(
                FitCube, self.GridFreqs, self.RefFreq)

        _, _, nx, ny = ModelImage.shape
        alphamap = np.zeros([nx, ny])
        Irefmap = np.zeros([nx, ny])
        alphastdmap = np.zeros([nx, ny])
        Irefstdmap = np.zeros([nx, ny])

        alphamap[MaskIndices[:, 0], MaskIndices[:, 1]] = alpha
        Irefmap[MaskIndices[:, 0], MaskIndices[:, 1]] = Iref
        alphastdmap[MaskIndices[:, 0], MaskIndices[:, 1]] = np.sqrt(varalpha)
        Irefstdmap[MaskIndices[:, 0], MaskIndices[:, 1]] = np.sqrt(varIref)

        if GiveComponents:
            return alphamap[None, None], alphastdmap[None, None], alpha
        else:
            return alphamap[None, None], alphastdmap[None, None]
示例#55
0
def test_fft_fractal():

    import matplotlib.pyplot as plt
    import matplotlib.cm as cm
    from matplotlib import rcParams
    import numpy as np
    
    from scipy import fftpack

    # this sets the size of the array. 
    array_power =10 
    array_size = 2**array_power
    
    # get now the beta value (that is, the slope of the
    # 1D power spectrum in log-log space)
    beta = 1.5
    
    print "array size is: " + str(array_size)
    
    # first make a random array   
    randarray = np.random.rand(array_size,array_size)
 
    plt.imshow(randarray)

    plt.show()
   
    # initialize the array for the inverse fourier transform
    freq_scaled_real = np.zeros((array_size,array_size))
    freq_scaled_imaginary = np.zeros((array_size,array_size))
        
    # print randarray
    
    # now get the FFT of the random surface
    F1 = fftpack.fft2(randarray)
    
    # get the FFT transformed data
    #F2 = fftpack.fftshift( F1 )  
    
  
    #plt.imshow(F2.real)

    #plt.show()


    #F2_backshift = np.fft.ifftshift(F2)
    #reconstruct = np.fft.ifft2(F2_backshift)
    
    #print "orig: "
    #print randarray
    
    #print "reconstruct: "
    #print reconstruct
    
    

    #plt.imshow(np.fft.ifft2(F2))
    #plt.show()

  
    # get the frequency coordinate
    freq = np.fft.fftfreq(array_size)    
    
    #freq = np.fft.fftshift(freqs)
    radial_freq = np.zeros((array_size,array_size))
    scaling = np.zeros((array_size,array_size))
    
    print "Frequency: " + str(freq)
       
    for row in range (0,array_size):
        for col in range (0,array_size):
            radial_freq[row][col] = np.sqrt(freq[row]**2+freq[col]**2)
            
            if (radial_freq[row][col] == 0):
                freq_scaled_real[row][col] = 0
                freq_scaled_imaginary[row][col] = 0
                scaling[row][col] = 0
            else:
                freq_scaled_real[row][col] = F1.real[row][col]/(radial_freq[row][col]**beta)
                freq_scaled_imaginary[row][col] = F1.imag[row][col]/(radial_freq[row][col]**beta)
                scaling[row][col] = 1/(radial_freq[row][col]**beta)
 
    #print "radial freq: "
    #print radial_freq
    
    #plt.imshow(freq_scaled_real)

    #plt.show()
    
    freq_scaled = freq_scaled_real + 1j*freq_scaled_imaginary
 
    #print "freq_scaled_real"
    #print freq_scaled_real
    
    #print "freq_scaled_imaginary"
    #print freq_scaled_imaginary
 
    #print "And freq_scaled: "
    #print freq_scaled

    #freq_scaled_backshift = np.fft.ifftshift(freq_scaled)
                      
    fractal_surf = np.fft.ifft2(freq_scaled)
    
    print "Factal surf is: "
    #print fractal_surf
    
    real_fracsurf = fractal_surf.real
        
    
    plt.imshow(real_fracsurf)

    plt.show()
示例#56
0
文件: dip2.py 项目: JoeyRxy/code
    plt.show()


############################
img = np.array(Image.open('Lenna.png'))[:, :, 0]
show(img, 'original')

sigma = 0.05
mu = 0
img = img + sigma * np.random.randn(img.shape[0], img.shape[1]) + mu
show(img, "img with noise")

H_ = H(img.shape[0], img.shape[1])
plot(np.abs(H_), 'H(u,v) amp')
plot(np.angle(H_), 'H(u,v) phase')
F_img = fftpack.fft2(img)
G = H_ * F_img  # 2-d的dft相乘时域也是圆周卷积吗??
G_r = fftpack.ifft2(G)
show(np.abs(G_r), 'After H(u,v)')
# %%
# 反向滤波
r0 = [1, 0.8, 0.5, 0.3]
for r in r0:
    xs = int(r * H_.shape[0])
    ys = int(r * H_.shape[1])
    H__ = np.ones(H_.shape)
    H__[:xs, :ys] = H_[:xs, :ys]
    img_rev = fftpack.ifft2(G / H__)
    psnr = PSNR(img_rev, img)
    show(np.abs(img_rev),
         'Inverse Filter : r0 = {} : PSNR = {} dB'.format(r, psnr))
示例#57
0
phi = np.zeros((N, N))


def pos(x):
    return int(N * x / L)


source = np.zeros((N, N))
source[pos(.4), 0] = -20 / dx**2
source[pos(.6), 0] = 20 / dx**2
L = (4 - np.exp(1.j * kxv * dx) - np.exp(-1.j * kxv * dx) -
     np.exp(1.j * kyv * dx) - np.exp(-1.j * kyv * dx)) / dx**2
L[0, 0] = 1  #freaks out at k=0

iters = 5
phik = fft2(source) / L
phik[0, 0] = 0
phi = np.real(ifft2(phik))
phi0 = np.copy(phi)

for i in range(iters):
    print i
    sourceeff = source - 100 * np.sin(phi)
    phik = fft2(sourceeff) / L
    phik[0, 0] = 0
    phi = np.real(ifft2(phik))

import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
示例#58
0
    def start(self, image_color, region):
        """
        image: numpy array of shape (width, height) for complete image
        region: bounding box of shape (width, height)

        Explanations:
        F as 2D Fourier transform of input image f
        H as 2D Fourier transform of filter h
        G = F * H^{*}, where {*} denotes the complex conjugate
        """
        image = np.sum(image_color, 2) / 3
        assert len(
            image.shape
        ) == 2, "Grayscale MOSSE is only defined for grayscale images"
        self.frame = 0
        self.region = region
        self.region_shape = (region.height, region.width)
        self.region_center = (region.height // 2, region.width // 2)

        self.search_region = region.rescale(self.search_size,
                                            round_coordinates=True)
        self.search_region_shape = (self.search_region.height,
                                    self.search_region.width)
        self.search_region_center = (self.search_region.height // 2,
                                     self.search_region.width // 2)

        patch = self.crop_patch(image)

        # pre-process the patch
        patch = pre_process(patch)
        # Fourier transform of patch
        F = fft2(patch)

        # initialise G as 2D Gaussian centered on the target
        Sigma = np.eye(2) * self.sigma**2
        mu = [self.search_region_center[0], self.search_region_center[1]]
        x, y = np.mgrid[0:self.search_region.height:1,
                        0:self.search_region.width:1]
        pos = np.dstack((x, y))
        r = multivariate_normal(mu, Sigma)
        g = r.pdf(pos)
        self.G = fft2(g)

        # compute numerator A and denominator B for H = A/B
        A = self.G * np.conj(F)
        B = F * np.conj(F)

        image_center = (self.region.xpos + self.region_center[1],
                        self.region.ypos + self.region_center[0])
        for angle in np.arange(-20, 20, 5):
            img_tmp = rotateImage(image_color, angle, image_center)  # Rotate
            img_tmp = np.sum(img_tmp, 2) / 3
            patch = self.crop_patch(img_tmp)
            patch = pre_process(patch)
            F = fft2(patch)
            A += self.G * np.conj(F)
            B += F * np.conj(F)

        # compute filter
        self.A = A
        self.B = B
        self.H_conj = self.A / (self.B + self.epsilon)

        if self.save_img and self.frame % self.save_frame == 0:
            plot(image_color, g.real, self.search_region,
                 "{0}_{1}".format(self.name, self.frame))
示例#59
0
# coding: utf-8

# In[3]:


import numpy as np
import matplotlib.pyplot as plt

from scipy.fftpack import ifft2, fft2, fftshift, fftfreq
from scipy import misc




imagenA = misc.imread('arbol.PNG')
FourierA = fft2(imagenA)
FourierA = FourierA/np.max(FourierA) # Guardar imagen

fig, ax = plt.subplots(figsize=(10,6))
ax.imshow(fftshift(np.abs(FourierA)))
fig.savefig('CaceresAlejandra_FT2D.pdf', type='pdf')



n = len(FourierA)
print (n)


# In[ ]:

示例#60
0
init_ampl = np.sqrt(im_bin)  ## Square of amplitude
init_ampl = init_ampl.astype(np.uint8)  ## Cast back to uint8

PS_shape = Beam_shape(SIZE_X, SIZE_Y, 255, 0)

u = np.zeros((SIZE_X, SIZE_Y), dtype=complex)
ampl = np.zeros((SIZE_X, SIZE_Y), dtype=complex)

ampl = join_phase_ampl(2 * np.pi * np.random.rand(SIZE_X, SIZE_Y) - np.pi,
                       init_ampl)

images = []
error = []

for x in range(20):
    u = sfft.fft2(ampl)
    u = sfft.fftshift(u)

    #The SLM renders the phase as multiple of 255 (255=2pi, 0 = 0pi). Some values of pi aren't permitted (discrete phase pattern)
    phase = np.round((np.angle(u) + np.pi) * 255 / (2 * np.pi))

    ## For plotting algorithm evol.
    SLM_phase = phase
    ## End of plotting

    #Back to the range [-pi,pi] but keeping the discretization imposed by the SLM (integers in [0,255])
    phase = phase / 255 * (2 * np.pi) - np.pi

    u = join_phase_ampl(phase, PS_shape.T)
    ampl = sfft.ifft2(u)
    #ampl = sfft.ifftshift(ampl)