本文整理汇总了Python中scipy.fftpack.fft2函数的典型用法代码示例。如果您正苦于以下问题:Python fft2函数的具体用法?Python fft2怎么用?Python fft2使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了fft2函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: colorize_by_power
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
示例2: correlate_layer
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)
示例3: shift_inner
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)
示例4: convolution_fourier_RGB
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
示例5: _storeLensKernel
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)
示例6: filters_bank
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
示例7: filters_bank
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
示例8: drawPic
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
示例9: frankotchellappa
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))
示例10: getGeneralStatistics
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
示例11: phase_cor
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
示例12: inverseFilter
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: solve
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
示例14: _getCrossCorrelation
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
示例15: step4
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
) ) ) )
) ) ) )
) ) ) )
) ) ) )
) ) ) )