def Convolve(image1, image2, MinPad=True, pad=True): """ Convolves image1 with image2. :param image1: 2D image array :param image2: 2D image array :param MinPad: whether to use minimal padding :param pad: whether to pad the array """ #The size of the images: r1, c1 = image1.shape r2, c2 = image2.shape if MinPad: r = r1 + r2 c = c1 + c2 else: r = 2*max(r1,r2) c = 2*max(c1,c2) #or in power of two if pad: pr2 = int(m.log(r)/m.log(2.) + 1.) pc2 = int(m.log(c)/m.log(2.) + 1.) rOrig = r cOrig = c r = 2**pr2 c = 2**pc2 fftimage = fft2(image1, s=(r,c))*fft2(image2[::-1,::-1],s=(r,c)) if pad: return (ifft2(fftimage))[:rOrig,:cOrig].real else: return (ifft2(fftimage)).real
def InitVelField(_N, _M, _h, h, dt, rho=1.0, mu=1.0, DeltaType=0): WideLambda = zeros((_N, _M), float64) ShortLambda = zeros((_N, _M), float64) IB_c.InitWideLaplacian(_N, _M, _h, WideLambda) IB_c.InitShortLaplacian(_N, _M, _h, ShortLambda) DxSymbol = InitDxSymbol(_N, _M, _h) DySymbol = InitDySymbol(_N, _M, _h) r = int(ceil(3.0 * h / _h)) fx = zeros((_N, _M), float64) for j in range(-r, r + 1): deltx = Delta(h, j * _h, DeltaType) for k in range(-r, r + 1): delt = deltx * Delta(h, k * _h, DeltaType) * 1.0 fx[j % _N][k % _M] = fx[j % _N][k % _M] + delt # print j%_N, k%_M, fx[j%_N][k%_M] fx, fy = fft2(dt * fx), zeros((_N, _M), float64) P = Solve_P_Hat(dt, WideLambda, DxSymbol, DySymbol, fx, fy) P[0, 0] = 0.0 u, v = Solve_uv_Hat(dt, ShortLambda, DxSymbol, DySymbol, P, fx, fy, rho, mu) u = 1.0 * ifft2(u).real v = 1.0 * ifft2(v).real # P = ifft2(P).real Fx1 = array(zeros((_N, _M), float64)) Fy1 = array(zeros((_N, _M), float64)) IB_c.WholeGridSpread(u, float(h), float(_h), int(r), Fx1, DeltaType) IB_c.WholeGridSpread(v, float(h), float(_h), int(r), Fy1, DeltaType) fy = zeros((_N, _M), float64) for j in range(-r, r + 1): deltx = Delta(h, j * _h, DeltaType) for k in range(-r, r + 1): delt = deltx * Delta(h, k * _h, DeltaType) * 1.0 fy[j % _N][k % _M] = fy[j % _N][k % _M] + delt # print j%_N, k%_M, fx[j%_N][k%_M] fx, fy = zeros((_N, _M), float64), fft2(dt * fy) P = Solve_P_Hat(dt, WideLambda, DxSymbol, DySymbol, fx, fy) P[0, 0] = 0.0 u, v = Solve_uv_Hat(dt, ShortLambda, DxSymbol, DySymbol, P, fx, fy, rho, mu) u = 1.0 * ifft2(u).real v = 1.0 * ifft2(v).real Fx2 = array(zeros((_N, _M), float64)) Fy2 = array(zeros((_N, _M), float64)) IB_c.WholeGridSpread(u, float(h), float(_h), int(r), Fx2, DeltaType) IB_c.WholeGridSpread(v, float(h), float(_h), int(r), Fy2, DeltaType) return Fx1, Fy1, Fx2, Fy2
def get_stat_spin_struct(filenames,nsamp): """ Gets the static structure factor flatened. The q-vectors are given by: q=arange(L) qx,qy=meshgrid(q,q) qx=qx.flatten() qy=qy.flatten() """ if type(filenames)!=list: filenames=[filenames] Sq=load.get_quantity(filenames,nsamp) params=load.get_attr(filenames[0]) Lx=int(params['L']) Ly=int(params['L']) hLx=int(Lx/2) hLy=int(Ly/2) N=Lx*Ly if Sq.shape[2]==N: # old file format, struct stored in Fourier components Sqxx=np.reshape(0.25*(Sq[:,1,:]+Sq[:,2,:]+Sq[:,3,:]+Sq[:,4,:]),(Sq.shape[0],Lx,Ly)) Sqyy=np.reshape(0.25*(Sq[:,1,:]+Sq[:,2,:]-Sq[:,3,:]-Sq[:,4,:]),(Sq.shape[0],Lx,Ly)) Sqzz=np.reshape(Sq[:,0,:],(Sq.shape[0],Lx.Ly)) Srxx=fft.fftshift(fft.fft2(Sqxx,axes=(1,2)),axes=(1,2))/N Sryy=fft.fftshift(fft.fft2(Sqyy,axes=(1,2)),axes=(1,2))/N Srzz=fft.fftshift(fft.fft2(Sqzz,axes=(1,2)),axes=(1,2))/N else : # new file format, struct stored as real space site pairs. rx,ry=np.meshgrid(np.arange(Lx,dtype=int),np.arange(Ly,dtype=int)) rx=rx.ravel() ry=ry.ravel() rix,rjx=np.meshgrid(rx,rx) riy,rjy=np.meshgrid(ry,ry) rijx=rjx-rix rijy=rjy-riy rijx[rijx>=hLx]-=Lx rijx[rijx<-hLx]+=Lx rijy[rijy>=hLy]-=Ly rijy[rijy<-hLy]+=Ly rijx=rijx.ravel() rijy=rijy.ravel() Sr=np.zeros((Sq.shape[0],5,N),dtype=complex) for samp in range(Sq.shape[0]): for t in range(N): Sr[samp,:,t]=np.sum(Sq[samp,:,np.where((rijy+hLy)*Lx+rijx+hLx==t)[0]],axis=0)/N Srxx=np.zeros((Sq.shape[0],Lx,Ly),dtype=complex) Sryy=np.zeros((Sq.shape[0],Lx,Ly),dtype=complex) Srzz=np.zeros((Sq.shape[0],Lx,Ly),dtype=complex) for samp in range(Sq.shape[0]): Srxx[samp,:,:]=np.reshape(0.25*np.sum(Sr[samp,1:,:],axis=0),(Lx,Ly)) Sryy[samp,:,:]=np.reshape(0.25*(np.sum(Sr[samp,1:3,:],axis=0)-np.sum(Sr[samp,3:,:],axis=0)),(Lx,Ly)) Srzz[samp,:,:]=np.reshape(Sr[samp,0,:],(Lx,Ly)) Sqxx=fft.ifft2(fft.fftshift(Srxx,axes=(1,2)),axes=(1,2))*N Sqyy=fft.ifft2(fft.fftshift(Sryy,axes=(1,2)),axes=(1,2))*N Sqzz=fft.ifft2(fft.fftshift(Srzz,axes=(1,2)),axes=(1,2))*N return (Sqxx,Sqyy,Sqzz),(Srxx,Sryy,Srzz)
def update_g(F, G_arg, C, iterations=1, eps=1e-9): G = G_arg.copy() g = ifft2(G) f_rev = np.rot90(ifft2(F), k=2) for k in range(int(iterations)): blur = (C / (G * F + eps)) * fft2(f_rev) G = fftconvolve(G, blur, "same") g = ifft2(blur) * g G = fft(g) return G, ifft2(G)
def do_n_extended_fits(nfits, xsh, ysh, imsize, gaussfit=False, maxoff=None, return_error=False, powerlaw=2.0, noise=1.0, unsharp_mask=False, smoothfactor=5, zeropad=0, shift_func=cross_correlation_shifts, sfkwargs={}, doplot=False, **kwargs): try: import progressbar widgets = [progressbar.FormatLabel('Processed: %(value)d offsets in %(elapsed)s)'), progressbar.Percentage()] progress = progressbar.ProgressBar(widgets=widgets) except ImportError: def progress(x): yield x image = make_extended(imsize, powerlaw=powerlaw) if zeropad > 0: newsize = [s+zeropad for s in image.shape] ylen,xlen = newsize xcen = xlen/2-(1-xlen%2) ycen = ylen/2-(1-ylen%2) newim = np.zeros(newsize) newim[ycen-image.shape[0]/2:ycen+image.shape[0]/2, xcen-image.shape[1]/2:xcen+image.shape[1]/2] = image image = newim if unsharp_mask: from AG_fft_tools import smooth offsets = [] for ii in progress(xrange(nfits)): inim = image-smooth(image,smoothfactor) offim = make_offset_extended(image, xsh, ysh, noise=noise, **kwargs) offim -= smooth(offim,smoothfactor) offsets.append( shift_func( inim, offim, return_error=return_error, **sfkwargs) ) else: offsets = [] if doplot: import pylab pylab.figure(3); pylab.subplot(221); pylab.imshow(image-image.mean()); pylab.subplot(222); pylab.imshow(offim-offim.mean()) #subplot(223); pylab.imshow((abs(fft2(image-image.mean())*conj(fft2(offim-offim.mean()))))) pylab.subplot(223); pylab.imshow(abs(ifft2((fft2(image)*conj(fft2(offim)))))) pylab.subplot(224); pylab.imshow(abs(ifft2((fft2(image-image.mean())*conj(fft2(offim-offim.mean())))))) draw() for ii in progress(xrange(nfits)): offim = make_offset_extended(image, xsh, ysh, noise=noise, **kwargs) offsets.append( shift_func( image, offim, return_error=return_error, **sfkwargs) ) return offsets
def F(wt, t, nu, KX, KY, K): # calculate psi in fourier space psit = -wt/K # calculate the derivatives of psi and w # in real space psi_x = np.real(fft.ifft2(1.j*KX*psit)) psi_y = np.real(fft.ifft2(1.j*KY*psit)) w_x = np.real(fft.ifft2(1.j*KX*wt)) w_y = np.real(fft.ifft2(1.j*KY*wt)) return fft.fft2(w_x*psi_y - w_y*psi_x) - nu*K*wt
def setUp(self): # Input self.data = hdf5.read_data("example_input.h5") C, T, Z, Y, X = self.data[0].shape self.data[0].shape = Y, X self.small_data = self.data[0][350:400, 325:375] # Input drifted by known value self.data_drifted = hdf5.read_data("example_drifted.h5") C, T, Z, Y, X = self.data_drifted[0].shape self.data_drifted[0].shape = Y, X # Input drifted by random value z = 1j # imaginary unit self.deltar = numpy.random.uniform(-100, 100) self.deltac = numpy.random.uniform(-100, 100) nr, nc = self.data[0].shape array_nr = numpy.arange(-numpy.fix(nr / 2), numpy.ceil(nr / 2)) array_nc = numpy.arange(-numpy.fix(nc / 2), numpy.ceil(nc / 2)) Nr = fft.ifftshift(array_nr) Nc = fft.ifftshift(array_nc) [Nc, Nr] = numpy.meshgrid(Nc, Nr) self.data_random_drifted = fft.ifft2(fft.fft2(self.data[0]) * numpy.power(math.e, z * 2 * math.pi * (self.deltar * Nr / nr + self.deltac * Nc / nc))) # Noisy inputs noise = random.normal(0, 3000, self.data[0].size) noise_array = noise.reshape(self.data[0].shape[0], self.data[0].shape[1]) self.data_noisy = self.data[0] + noise_array self.data_drifted_noisy = self.data_drifted[0] + noise_array self.data_random_drifted_noisy = self.data_random_drifted + noise_array # Small input drifted by random value self.small_deltar = numpy.random.uniform(-10, 10) self.small_deltac = numpy.random.uniform(-10, 10) nr, nc = self.small_data.shape array_nr = numpy.arange(-numpy.fix(nr / 2), numpy.ceil(nr / 2)) array_nc = numpy.arange(-numpy.fix(nc / 2), numpy.ceil(nc / 2)) Nr = fft.ifftshift(array_nr) Nc = fft.ifftshift(array_nc) [Nc, Nr] = numpy.meshgrid(Nc, Nr) self.small_data_random_drifted = fft.ifft2(fft.fft2(self.small_data) * numpy.power(math.e, z * 2 * math.pi * (self.small_deltar * Nr / nr + self.small_deltac * Nc / nc))) # Small noisy inputs small_noise = random.normal(0, 3000, self.small_data.size) small_noise_array = small_noise.reshape(self.small_data.shape[0], self.small_data.shape[1]) self.small_data_noisy = self.small_data + small_noise_array self.small_data_random_drifted_noisy = self.small_data_random_drifted + small_noise_array
def task3_2(): print('3.2') low_pass = normalize_intensity(imread(LOW_PASS)) high_pass = normalize_intensity(imread(HIGH_PASS)) img_freq_dom = fft2(a=normalize_intensity(imread(BRICKS_2))) apply_low_pass = img_freq_dom * low_pass ifft_res = ifft2(a=apply_low_pass) output_path = os.path.join(OUTPUT_DIR, "3_2_low_pass_" + os.path.split(BRICKS_2)[-1]) imsave(output_path, abs(ifft_res)) apply_high_pass = img_freq_dom * high_pass ifft_res = ifft2(a=apply_high_pass) output_path = os.path.join(OUTPUT_DIR, "3_2_high_pass_" + os.path.split(BRICKS_2)[-1]) imsave(output_path, abs(ifft_res))
def remove_lowest(shape, dim=1): x_min = amin(real(fft.ifft2(change_n(shape.x_hat, 1E2 * ones(FFT_NDIM)), axes=FFT_AXES))[...,dim]) g = 1/(5*absolute(shape.x[...,dim] - x_min) + 0.5) - 0.5 g[g<0] = 0 return g
def unwhite(arr4d, cachename): assert cachename in whiteconfs subterm, divterm, fftterm = whiteconfs[cachename] farr4d = fft.fft2(arr4d) farr4d = farr4d / fftterm arr4d = np.real(fft.ifft2(farr4d)) return arr4d
def applyPreconditioner(self, arr): ftMap = fft2(arr) Ny = (arr.shape)[0] Nx = (arr.shape)[1] pixScaleX = ( numpy.abs(self.ra1 - self.ra0) / Nx * numpy.pi / 180.0 * numpy.cos(numpy.pi / 180.0 * 0.5 * (self.dec0 + self.dec1)) ) pixScaleY = numpy.abs(self.dec1 - self.dec0) / Ny * numpy.pi / 180.0 lx = 2 * numpy.pi * fftfreq(Nx, d=pixScaleX) ly = 2 * numpy.pi * fftfreq(Ny, d=pixScaleY) ix = numpy.mod(numpy.arange(Nx * Ny), Nx) iy = numpy.arange(Nx * Ny) / Nx lMap = ftMap * 0.0 lMap[iy, ix] = numpy.sqrt(lx[ix] ** 2 + ly[iy] ** 2) lOverl0 = lMap / self.l0 Fl = self.A * ((lOverl0) ** self.alpha) / (1.0 + lOverl0 ** self.alpha) filteredFtMap = ftMap / Fl filteredFtMap[0, 0] = 0.0 # avoids nan and makes mean 0 arr[:, :] = (numpy.real(ifft2(filteredFtMap)))[:, :]
def InvLaplacian(field, length=None): if length is None: length = 2*pi; N = shape(field)[0]; k = array(range(N),dtype=complex128); k = concatenate((range(0,N/2),range(-N/2,0))); k *= (2*pi)/length; [KX, KY] = meshgrid(k,k); """ We are trying to solve d_yy(eta) + d_xx(eta) = p Therefore, in Fourier space, it will become (-(kx^2 + ky^2) )etaHat = pHat """ delsq = -(KX*KX + KY*KY) ; delsq[0,0] = 1; # tmp = fft(field,axis=0); # tmp = fft(tmp,axis=1); tmp = fft2(field); tmp = tmp/delsq; [xval,yval] = shape(tmp); tmp[xval/3:2*xval/3,yval/3:2*yval/3] = 0; # tmp = ifft(tmp,axis=1); # tmp = ifft(tmp,axis=0); tmp = ifft2(tmp); return tmp.real;
def whiten_olsh_lee_inner(image, f_0=None, central_clip=(None, None), normalize_pre=True, normalize_post=True, no_filter=False): height, width = image.shape assert height % 2 == 0 and width % 2 == 0, "image must have even size!" if normalize_pre: image = image - image.mean() # I personally think this is useless, since rho will make (0,0) freq compoenent 0. std_im = image.std(ddof=1) assert std_im != 0, "constant image unsupported!" image /= std_im fx, fy = np.meshgrid(np.arange(-height / 2, height / 2), np.arange(-width / 2, width / 2), indexing='ij') rho = np.sqrt(fx * fx + fy * fy) if f_0 is None: f_0 = 0.4 * (height + width) / 2 filt = rho * np.exp(-((rho / f_0) ** 4)) im_f = fft2(image) if not no_filter: fft_filtered_old = im_f * ifftshift(filt) else: # hack to only lower frequency response. print('no real filtering!') fft_filtered_old = im_f fft_filtered_old = fftshift(fft_filtered_old) if central_clip != (None, None): fft_filtered_old = fft_filtered_old[height // 2 - central_clip[0] // 2:height // 2 + central_clip[0] // 2, width // 2 - central_clip[1] // 2:width // 2 + central_clip[1] // 2] im_out = np.real(ifft2(ifftshift(fft_filtered_old))) # I believe since the rho at the (0,0) frequency part is zero, then the whole image should be zero as well. # so explicit DC removing is useless. if normalize_post: assert abs(im_out.mean()) < 1e-6 # should be extremely small. std_im_out = im_out.std(ddof=1) else: std_im_out = 1 return im_out / std_im_out
def compute(self, scene: Scene): """ Compute optical irradiance map Computation proccedure: 1) convert radiance to irradiance 2) apply lens and macular transmittance 3) apply off-axis fall-off (cos4th) 4) apply optical transfert function Args: scene (pyEyeBall.Scene): instance of Scene class, containing the radiance and other scene information Examples: >>> oi = Optics() >>> oi.compute(Scene()) """ # set field of view and wavelength samples self.fov = scene.fov scene.wave = self._wave self.dist = scene.dist # compute irradiance self.photons = pi / (1 + 4 * self.f_number**2 * (1 + abs(self.magnification))**2) * scene.photons # apply ocular transmittance self.photons *= self.ocular_transmittance # apply the relative illuminant (off-axis) fall-off: cos4th function x, y = self.spatial_support s_factor = np.sqrt(self.image_distance**2 + x**2 + y**2) self.photons *= (self.image_distance / s_factor[:, :, None])**4 # apply optical transfer function of the optics for ii in range(self.wave.size): otf = fftshift(self.otf(self._wave[ii], self.frequency_support_x, self.frequency_support_y)) self.photons[:, :, ii] = np.abs(ifftshift(ifft2(otf * fft2(fftshift(self.photons[:, :, ii])))))
def create_matching_kernel(source_psf, target_psf, window=None): """ Create a kernel to match 2D point spread functions (PSF) using the ratio of Fourier transforms. Parameters ---------- source_psf : 2D `~numpy.ndarray` The source PSF. The source PSF should have higher resolution (i.e. narrower) than the target PSF. ``source_psf`` and ``target_psf`` must have the same shape and pixel scale. target_psf : 2D `~numpy.ndarray` The target PSF. The target PSF should have lower resolution (i.e. broader) than the source PSF. ``source_psf`` and ``target_psf`` must have the same shape and pixel scale. window : callable, optional The window (or taper) function or callable class instance used to remove high frequency noise from the PSF matching kernel. Some examples include: * `~photutils.psf.matching.HanningWindow` * `~photutils.psf.matching.TukeyWindow` * `~photutils.psf.matching.CosineBellWindow` * `~photutils.psf.matching.SplitCosineBellWindow` * `~photutils.psf.matching.TopHatWindow` For more information on window functions and example usage, see :ref:`psf_matching`. Returns ------- kernel : 2D `~numpy.ndarray` The matching kernel to go from ``source_psf`` to ``target_psf``. The output matching kernel is normalized such that it sums to 1. """ # inputs are copied so that they are not changed when normalizing source_psf = np.copy(np.asanyarray(source_psf)) target_psf = np.copy(np.asanyarray(target_psf)) if source_psf.shape != target_psf.shape: raise ValueError('source_psf and target_psf must have the same shape ' '(i.e. registered with the same pixel scale).') # ensure input PSFs are normalized source_psf /= source_psf.sum() target_psf /= target_psf.sum() source_otf = fftshift(fft2(source_psf)) target_otf = fftshift(fft2(target_psf)) ratio = target_otf / source_otf # apply a window function in frequency space if window is not None: ratio *= window(target_psf.shape) kernel = np.real(fftshift((ifft2(ifftshift(ratio))))) return kernel / kernel.sum()
def _simulate_image(self): """ Generates the fake output. """ with self._acquisition_init_lock: pos = self.align.position.value logging.debug("Simulating image shift by %s", pos) ac, bc = pos.get("a"), pos.get("b") ang = math.radians(135) # AB->XY xc = -(ac * math.sin(ang) + bc * math.cos(ang)) yc = -(ac * math.cos(ang) - bc * math.sin(ang)) pixelSize = self.fake_img.metadata[model.MD_PIXEL_SIZE] self.fake_img.metadata[model.MD_ACQ_DATE] = time.time() x_pxs = xc / pixelSize[0] y_pxs = yc / pixelSize[1] # Image shifted based on LensAligner position z = 1j # imaginary unit self.deltar = x_pxs self.deltac = y_pxs nr, nc = self.fake_img.shape array_nr = numpy.arange(-numpy.fix(nr / 2), numpy.ceil(nr / 2)) array_nc = numpy.arange(-numpy.fix(nc / 2), numpy.ceil(nc / 2)) Nr = fft.ifftshift(array_nr) Nc = fft.ifftshift(array_nc) [Nc, Nr] = numpy.meshgrid(Nc, Nr) sim_img = fft.ifft2(fft.fft2(self.fake_img) * numpy.power(math.e, z * 2 * math.pi * (self.deltar * Nr / nr + self.deltac * Nc / nc))) output = model.DataArray(abs(sim_img), self.fake_img.metadata) return output
def cross_corr(img1,img2,mask=None): '''Compute the autocorrelation of two images. Right now does not take mask into account. todo: take mask into account (requires extra calculations) input: img1: first image img2: second image mask: a mask array output: the autocorrelation of the two images (same shape as the correlated images) ''' #if(mask is not None): # img1 *= mask # img2 *= mask #img1_mean = np.mean( img1.flat ) #img2_mean = np.mean( img2.flat ) # imgc = fftshift( ifft2( # fft2(img1/img1_mean -1.0 )*np.conj(fft2( img2/img2_mean -1.0 ))).real ) #imgc = fftshift( ifft2( # fft2( img1/img1_mean )*np.conj(fft2( img2/img2_mean ))).real ) imgc = fftshift( ifft2( fft2( img1 )*np.conj(fft2( img2 ))).real ) #imgc /= (img1.shape[0]*img1.shape[1])**2 if(mask is not None): maskc = cross_corr(mask,mask) imgc /= np.maximum( 1, maskc ) return imgc
def icwt2d(W, a, dx=0.25, dy=0.25, da=0.25, wavelet=Mexican_hat()): """ Inverse bi-dimensional continuous wavelet transform as in Wang and Lu (2010), equation [5]. PARAMETERS W (array like): Wavelet transform, the result of the cwt2d function. a (array like, optional): Scale parameter array. w (class, optional) : Mother wavelet class. Default is Mexican_hat() RETURNS iW (array like) : Inverse wavelet transform. EXAMPLE """ m0, l0, k0 = W.shape if m0 != a.size: raise Warning('Scale parameter array shape does not match wavelet' \ ' transform array shape.') # Calculates the zonal and meridional wave numters. L, K = 2 ** int(ceil(log2(l0))), 2 ** int(ceil(log2(k0))) # Calculates the zonal and meridional wave numbers. l, k = fftfreq(L, dy), fftfreq(K, dx) # Creates empty inverse wavelet transform array and fills it for every # discrete scale using the convolution theorem. iW = zeros((m0, L, K), 'complex') for i, an in enumerate(a): psi_ft_bar = an * wavelet.psi_ft(an * k, an * l) W_ft = fft2(W[i, :, :], s=(L, K)) iW[i, :, :] = ifft2(W_ft * psi_ft_bar, s=(L, K)) * da / an ** 2. return iW[:, :l0, :k0].real.sum(axis=0) / wavelet.cpsi
def filterDFT(imageMatrix, filterMatrix): shiftedDFT = fftshift(fft2(imageMatrix)) misc.imsave("dft.png", scaleSpectrum(shiftedDFT)) filteredDFT = shiftedDFT * filterMatrix misc.imsave("filtered-dft.png", scaleSpectrum(filteredDFT)) return ifft2(ifftshift(filteredDFT))
def delay_fringe_rate(tf_plane,padding=1): if isnan(tf_plane).sum() > 0: ValueError('*tf_plane* contains NaN values. Please sanitize it before plotting using, e.g. tf_plane[isnan(tf_plane)] == 0.0, or pyautoplot.utilities.set_nan_zero(tf_plane)') nt,nf = tf_plane.shape padded_plane=zeros((nt,padding*nf),dtype=complex64) padded_plane[:,(padding//2):(padding//2+nf)] = tf_plane.data*logical_not(tf_plane.mask) return fftshift(ifft2(padded_plane))
def high_pass_filter(img, filtersize=10): """ A FFT implmentation of high pass filter from pyKLIP. Args: img: a 2D image filtersize: size in Fourier space of the size of the space. In image space, size=img_size/filtersize Returns: filtered: the filtered image """ if filtersize == 0: return img # mask NaNs nan_index = np.where(np.isnan(img)) img[nan_index] = 0 transform = fft.fft2(img) # coordinate system in FFT image u,v = np.meshgrid(fft.fftfreq(transform.shape[1]), fft.fftfreq(transform.shape[0])) # scale u,v so it has units of pixels in FFT space rho = np.sqrt((u*transform.shape[1])**2 + (v*transform.shape[0])**2) # scale rho up so that it has units of pixels in FFT space # rho *= transform.shape[0] # create the filter filt = 1. - np.exp(-(rho**2/filtersize**2)) filtered = np.real(fft.ifft2(transform*filt)) # restore NaNs filtered[nan_index] = np.nan img[nan_index] = np.nan return filtered
def F(t, wt2, nu, K, K2, n, KX, KY): # reshape 1d array into 2d array wt = wt2.reshape(n, n) # calculate psi in fourier space psit = -wt/K # calculate the derivatives of psi and w # in real space psi_x = np.real(fft.ifft2(1.j*KX*psit)) psi_y = np.real(fft.ifft2(1.j*KY*psit)) w_x = np.real(fft.ifft2(1.j*KX*wt)) w_y = np.real(fft.ifft2(1.j*KY*wt)) return fft.fft2(w_x*psi_y - w_y*psi_x).flatten() - nu*K2*wt2
def on_timer(self, *args): if not self.need_redraw: return self.need_redraw = False self.mask.fill(0) length = len(self.lasso_selection.dataspace_points) if length == 0: return def convert_poly(poly): tmp = cv.asvector_Point2i(poly) return cv.vector_vector_Point2i([tmp]) # 在遮罩数组上绘制套索多边形 for poly in self.lasso_selection.disjoint_selections: poly = poly.astype(np.int) print poly.shape cv.fillPoly(self.mask_img, convert_poly(poly), cv.Scalar(1,1,1,1)) poly = N - poly # 绘制对称多边形 cv.fillPoly(self.mask_img, convert_poly(poly), cv.Scalar(1,1,1,1)) # 更新遮罩图像 self.data["mask_img"] = self.mask # 更新滤波图像 data = self.data["filtered_img"] data[:] = fft.ifft2(self.fimg * fft.fftshift(self.mask)).real self.data["filtered_img"] = data
def acf(x, axes=(0,1)): """ 2D ACF using fft Inputs: x is ndarray with shape (nt, nx) """ from numpy.fft import fft2, ifft2, fftshift if x.ndim == 1: x = x[:,None] elif x.ndim == 2: pass else: raise NotImplementedError nt, nx = x.shape padding = np.zeros((nt, nx)) x = np.concatenate((x, padding)) fx = fft2(x, axes=axes) ac= np.real(ifft2(fx * np.conj(fx), axes=axes))[:(nt-10),:] / nx / np.arange(nt, 10, -1)[:,None] ac = ac[:nt/2, :nx/2] return ac
def blur_image(self, image, b_length, b_theta): """ Return a blurred image Inputs: image -- x by y image (gabor wavelet in this case) (list) b_length -- length of blur b_theta -- angle of blur Outputs: blurred -- blurred x by y image (list) """ x,y = shape(image) #x and y switched because the result of shape refers to #columns and rows self.face_y = x self.face_x = y h = filt_mblur(b_length, b_theta) H = psf2otf(h, (x,y)) self.blur_resp = H Image = fft2(image) Blurred = multiply(H,Image) blurred = ifft2(Blurred) return blurred
def calculate(imageFFT, phaseSymmetry, symmetryTotal, amplitudeTotal): for a in range(1,orientations + 1): #print(a) symmetryAtOrientation = np.zeros((image.shape[0], image.shape[1])) amplitudeAtOrientation = np.zeros((image.shape[0], image.shape[1])) for n in range(scales): kernel = bank[a - 1][n] convolved = imageFFT * kernel s1 = np.array(kernel.shape) s2 = np.array(imageFFT.shape) convolved = fft.ifft2(convolved) evens = np.real(convolved) odds = np.imag(convolved) amplitude = np.sqrt(np.power(evens, 2) + np.power(odds, 2)) amplitudeAtOrientation += amplitude symmetryAtOrientation += np.maximum((np.abs(evens) - np.abs(odds)) , floor) amplitudeTotal += np.add(amplitudeAtOrientation, 0.00001) symmetryTotal += symmetryAtOrientation phaseSymmetry = np.divide(symmetryTotal , amplitudeTotal) phaseSymmetry[mask < 0.2] = 0.0 return phaseSymmetry
def subpixel_shift(img_arr, dx=0.5, inplace=True): ''' Shifts an image by a fraction of a pixel in a random direction, with circular boundary conditions. Arguments: img_arr (2D ndarray): array to subpixel shift in a random direction dx (float): distance in pixel to shift by inplace (bool): if True, will modify the array inplace ''' f = fft.fft2(img_arr, axes=(0, 1)) g = np.meshgrid( fft.fftfreq(img_arr.shape[-3]), fft.fftfreq(img_arr.shape[-2]) ) u = npr.normal(0, 1, size=2) fk = g[0] * u[0] + g[1] * u[1] phi = np.exp(2j * np.pi * dx * fk) out = np.real(fft.ifft2(phi[..., np.newaxis] * f, axes=(0, 1))) if inplace: img_arr[:] = out[:] else: return out
def circulantPinkNoiseIterator(p, powerspectrum_sample_size, patchSampler, orientation='F'): """ Samples pxp patches from circulant pink noise with power spectrum from patchSampler. The images are vectorized in FORTRAN/MATLAB style by default. :param p: patch size :type p: int :param powerspectrum_sample_size: number of patches to sample from sampler for power spectrum :type powerspectrum_sample_size: int :param patchSampler: Iterator to sample patches from :type patchSampler: Iterator :param orientation: 'C' (C/Python, row-major) or 'F' (FORTRAN/MATLAB, column-major) vectorized patches :type orientation: string :returns: Iterator that samples from all files :rtype: Iterator """ patches = zeros((p**2, powerspectrum_sample_size)) stdout.write('Initialize power spectrum of circulant pink noise generator. This may take a moment...\n') stdout.flush() for ii in xrange(powerspectrum_sample_size): patches[:,ii] = patchSampler.next() PATCHES = fft.fft2(patches.reshape(p,p,powerspectrum_sample_size), axes=(0,1)) powerspec = (PATCHES*PATCHES.conj()).mean(2).real stdout.write('Powerspectrum completed.\n') while True: phi = rand(p,p)*2*pi - pi X = fft.ifft2(sqrt(powerspec)*exp(1J*phi), axes=(0,1)).real.flatten(orientation) yield X return
def _step(self): fft2,ifft2 = self.get_fft() if self._F_is_constant: self.__freq_data *= self.__D_step * self.__R_step self.__data = ifft2(self.__freq_data) elif self._F_is_constant_in_z: self.__freq_data = fft2(self.__data) self.__freq_data *= self.__D_step self.__data = ifft2(self.__freq_data) self.__data *= self.__R_step else: self.__freq_data = fft2(self.__data) self.__freq_data *= self.__D_step self.__data = ifft2(self.__freq_data) self.__data *= self.__R(*self._get_coordinates())
def gradient_helper(self, x, shape, ctr): """Not sure exactly what this does yet. Parameters ---------- i_t : int Epoch index. x : np.ndarray (3-d) Same shape as *data* for single epoch (nw, ny, nx). xcoords : np.ndarray (1-d) ycoords : np.ndarray (1-d) Returns ------- x : np.ndarray (3-d) Shape is (nw, len(ycoords), len(xcoords)). """ # shift necessary to put model onto data coordinates offset = yxoffset((self.ny, self.nx), shape, ctr) fshift = fft_shift_phasor_2d((self.ny, self.nx), (-offset[0], -offset[1])) fshift = np.asarray(fshift, dtype=self.complex_dtype) # create output array out = np.zeros((self.nw, self.ny, self.nx), dtype=self.dtype) out[:, : x.shape[1], : x.shape[2]] = x for i in range(self.nw): tmp = ifft2(np.conj(self.fftconv[i, :, :] * fshift) * fft2(out[i, :, :])) out[i, :, :] = tmp.real return out
def calc_2nd_cumulant(v1, v2=None, mask=None, axes=(-2, -1)): """ Calculate 2nd-order cumulant of v1 and v2 in Fourier space. If mask is supplied the region outside the mask is set to the mean of the masked region, so that this region does not contribute to the cumulant If axes is a sequence with only one item then the cumulant is only calculated along that axis and the others are left unchanged. """ if v2 is not None: assert v1.shape == v2.shape assert v1.dims == v2.dims assert len(axes) in [1, 2] v_shape = v1.shape x_dim = v1.dims[axes[0]] Nx = v_shape[axes[0]] if len(axes) == 1: mean_axis = axes[0] else: mean_axis = None y_dim = v1.dims[axes[1]] Ny = v_shape[axes[1]] old_attrs = v1.attrs v1 = v1 - v1.mean(axis=mean_axis) v1.attrs = old_attrs if v2 is not None: v2_old_attrs = v2.attrs v2 = v2 - v2.mean(axis=mean_axis) v2.attrs = v2_old_attrs if mask is not None: assert v1.shape == mask.shape assert v1.dims == mask.dims # set outside the masked region to the mean so that values in this # region don't correlate with the rest of the domain v1 = v1.where(mask.values, other=0.0) if v2 is not None: v2 = v2.where(mask.values, other=0.0) V1 = fft.fft2(v1, axes=axes) if v2 is None: v2 = v1 V2 = V1 else: V2 = fft.fft2(v2, axes=axes) c_vv_fft = fft.ifft2(V1 * V2.conjugate(), axes=axes) c_vv = c_vv_fft.real / Nx if len(axes) == 2: c_vv /= Ny # it's most handy to have this centered on (0,0) c_vv = np.roll(c_vv, shift=int(Nx / 2), axis=axes[0]) if len(axes) == 2: c_vv = np.roll(c_vv, shift=int(Ny / 2), axis=axes[1]) # let's give it a useful name and description long_name = r"$C({},{})$".format( _var_name_mapping.get(v1.name, v1.long_name), _var_name_mapping.get(v2.name, v2.long_name), ) v1_name = v1.name if v1.name is not None else v1.long_name v2_name = v2.name if v2.name is not None else v2.long_name name = "C({},{})".format(v1_name, v2_name) # create displacement coordinate for cumulant data def _calc_offset_coord(v_coord): if np.issubdtype(v_coord.dtype, np.datetime64): # for datetime we could use timedelta, but matplotlib can't plot # these and so we convert to number of seconds here v_center = v_coord.min() + 0.5 * (v_coord.max() - v_coord.min()) v_coord_new = v_coord - v_center v_coord_new = xr.DataArray( v_coord_new.values.astype("timedelta64[ns]").astype(int) / 1.0e9, dims=v_coord.dims, attrs=dict(units="s"), ) else: v_coord_new = v_coord - 0.5 * (v_coord.min() + v_coord.max()) v_coord_new.attrs.update(v_coord.attrs) return v_coord_new x_cvv = _calc_offset_coord(v1[x_dim]) # start of with original coords coords_cvv = v1.coords coords_cvv[x_dim] = x_cvv if len(axes) == 2: y_cvv = _calc_offset_coord(v1[y_dim]) coords_cvv[y_dim] = y_cvv if mask is not None: long_name = "{} masked by {}".format(long_name, mask.long_name) attrs = dict(units="{} {}".format(v1.units, v2.units), long_name=long_name) return xr.DataArray(c_vv, dims=v1.dims, coords=coords_cvv, attrs=attrs, name=name)
def measure_offset_from_ffts(img0_fft2, img1_fft2, withLog=False): """ Convenience method to measure the actual offset between 2 images taing their FFTs as inpuy The first FFT one is the one of the reference. That means, if the image to be shifted is the second one, the shift has to be multiplied byt -1. :param img1: ndarray, FFT of first image :param img2: ndarray, FFT of the second image, same shape as img1 :param withLog: shall we return logs as well ? boolean :return: tuple of floats with the offsets of the second respect to the first """ shape = img0_fft2.shape logs = [] f0 = img0_fft2 f1 = img1_fft2 t0 = time.time() absf0 = abs(f0) absf1 = abs(f1) if 0: # one way to deal with zeros if (absf0 < 1.0e-20).any() or (absf1 < 1.0e-20).any(): ofsset = [0.0, 0.0] logs.append("MeasureOffset: empty or uniform image?") if withLog: return offset, logs else: return offset else: # this one seems better because numerator is expected to be zero idx = absf0 < 1.0e-20 if idx.any(): absf0[idx] = 1.0 idx = absf1 < 1.0e-20 if idx.any(): absf1[idx] = 1.0 res = abs(fftshift(ifft2((f0 * f1.conjugate()) / (absf0 * absf1)))) t1 = time.time() a0, a1 = numpy.unravel_index(numpy.argmax(res), shape) resmax = res[a0, a1] coarse_result = (shape[0] // 2 - a0, shape[1] // 2 - a1) logs.append("ImageRegistration: coarse result : %d %d " % \ (coarse_result[0], coarse_result[1])) # refine a bit the position w = 3 x0 = 0.0 x1 = 0.0 total = 0.0 a00 = int(max(a0 - w, 0)) a01 = int(min(a0 + w + 1, shape[0])) a10 = int(max(a1 - w, 0)) a11 = int(min(a1 + w + 1, shape[1])) if a00 == a01: a01 = a00 + 1 if a10 == a11: a11 = a10 + 1 for i in range(a00, a01): for j in range(a10, a11): if res[i, j] > 0.1 * resmax: tmp = res[i, j] x0 += i * tmp x1 += j * tmp total += tmp offset = [shape[0] // 2 - x0 / total, shape[1] // 2 - x1 / total] logs.append( "MeasureOffset: fine result of the centered image: %.3f %.3fs " % (offset[0], offset[1])) t3 = time.time() logs.append("Total execution time %.3fs" % (t3 - t0)) if withLog: return offset, logs else: return offset
def similarity(bn0, bn1): """Register bn1 to bn0 , M. Canty 2012 bn0, bn1 and returned result are image bands Modified from Imreg.py, see http://www.lfd.uci.edu/~gohlke/: Copyright (c) 2011-2012, Christoph Gohlke Copyright (c) 2011-2012, The Regents of the University of California Produced at the Laboratory for Fluorescence Dynamics All rights reserved. """ def highpass(shape): """Return highpass filter to be multiplied with fourier transform.""" x = np.outer( np.cos(np.linspace(-math.pi / 2., math.pi / 2., shape[0])), np.cos(np.linspace(-math.pi / 2., math.pi / 2., shape[1]))) return (1.0 - x) * (2.0 - x) def logpolar(image, angles=None, radii=None): """Return log-polar transformed image and log base.""" shape = image.shape center = shape[0] / 2, shape[1] / 2 if angles is None: angles = shape[0] if radii is None: radii = shape[1] theta = np.empty((angles, radii), dtype=np.float64) theta.T[:] = -np.linspace(0, np.pi, angles, endpoint=False) # d = radii d = np.hypot(shape[0] - center[0], shape[1] - center[1]) log_base = 10.0 ** (math.log10(d) / (radii)) radius = np.empty_like(theta) radius[:] = np.power(log_base, np.arange(radii, dtype = np.float64)) - 1.0 x = radius * np.sin(theta) + center[0] y = radius * np.cos(theta) + center[1] output = np.empty_like(x) ndii.map_coordinates(image, [x, y], output=output) return output, log_base lines0, samples0 = bn0.shape # make reference and warp bands same shape bn1 = bn1[0:lines0, 0:samples0] # get scale, angle f0 = fftshift(abs(fft2(bn0))) f1 = fftshift(abs(fft2(bn1))) h = highpass(f0.shape) f0 *= h f1 *= h del h f0, log_base = logpolar(f0) f1, log_base = logpolar(f1) f0 = fft2(f0) f1 = fft2(f1) r0 = abs(f0) * abs(f1) ir = abs(ifft2((f0 * f1.conjugate()) / r0)) i0, i1 = np.unravel_index(np.argmax(ir), ir.shape) angle = 180.0 * i0 / ir.shape[0] scale = log_base ** i1 if scale > 1.8: ir = abs(ifft2((f1 * f0.conjugate()) / r0)) i0, i1 = np.unravel_index(np.argmax(ir), ir.shape) angle = -180.0 * i0 / ir.shape[0] scale = 1.0 / (log_base ** i1) if scale > 1.8: raise ValueError("Images are not compatible. Scale change > 1.8") if angle < -90.0: angle += 180.0 elif angle > 90.0: angle -= 180.0 # re-scale and rotate and then get shift bn2 = ndii.zoom(bn1, 1.0 / scale) bn2 = ndii.rotate(bn2, angle) if bn2.shape < bn0.shape: t = np.zeros_like(bn0) t[:bn2.shape[0], :bn2.shape[1]] = bn2 bn2 = t elif bn2.shape > bn0.shape: bn2 = bn2[:bn0.shape[0], :bn0.shape[1]] f0 = fft2(bn0) f1 = fft2(bn2) ir = abs(ifft2((f0 * f1.conjugate()) / (abs(f0) * abs(f1)))) t0, t1 = np.unravel_index(np.argmax(ir), ir.shape) if t0 > f0.shape[0] // 2: t0 -= f0.shape[0] if t1 > f0.shape[1] // 2: t1 -= f0.shape[1] # return result return (scale, angle, [t0, t1])
def inverse(input, PSF, eps): # 逆滤波 input_fft = fft.fft2(input) PSF_fft = fft.fft2(PSF) + eps #噪声功率,这是已知的,考虑epsilon result = fft.ifft2(input_fft / PSF_fft) #计算F(u,v)的傅里叶反变换 result = np.abs(fft.fftshift(result)) return result
plt.xlim([0, 1]) plt.legend(title='Slice') plt.xlabel('PV Defocus [$\lambda$]') plt.ylabel('Relative power') plt.grid(True) plt.show() """ Fourier stuff """ """ (1) Pupil Plane """ pupil_f = pupil * np.exp(2 * np.pi * 1j * np.zeros_like(pupil)) """ (2) Slicer Focal Plane """ slicer_plane = fftshift(fft2(pupil_f)) # Mask one Slice masked_slicer = mask_slice * slicer_plane slicer_image = (np.abs(masked_slicer))**2 / PEAK """ (3) Pupil Plane""" pupil_mirror = ifft2(fftshift(masked_slicer)) pupil_image = (np.abs(pupil_mirror))**2 # pup_pix = int(3*N_PIX /4) pup_pix = int(N_PIX / 4) # Pupil Mirror Aperture mask_pupil = np.zeros((N_PIX, N_PIX)).astype(bool) mask_pupil[(N_PIX - pup_pix) // 2:(N_PIX + pup_pix) // 2, :] = True # masked_pupil_image = mask_pupil * pupil_image masked_pupil_image = mask_pupil * pupil_image # Real and Imaginary part of Pupil Mirror E_field plt.figure() plt.plot(np.real(pupil_mirror)[:, N_PIX // 2]) # plt.axvline((N_PIX-pup_pix)//2, color='black', linestyle='--') # plt.axvline((N_PIX+pup_pix)//2, color='black', linestyle='--')
def phasecong2(im): nscale = 4 norient = 4 minWaveLength = 6 mult = 2 sigmaOnf = 0.55 dThetaOnSigma = 1.2 k = 2.0 epsilon = .0001 thetaSigma = np.pi / norient / dThetaOnSigma _, _, rows, cols = im.shape imagefft = torch.rfft(im, 2, onesided=False) lp = lowpassfilter((rows, cols), .45, 15) radius, _, _ = filtergrid(rows, cols) radius[0, 0] = 1. logGaborList = [] logGaborDenom = 2. * np.log(sigmaOnf)**2. for s in range(nscale): wavelength = minWaveLength * mult**s fo = 1. / wavelength # Centre frequency of filter logRadOverFo = (np.log(radius / fo)) logGabor = np.exp(-(logRadOverFo * logRadOverFo) / logGaborDenom) logGabor *= lp # Apply the low-pass filter logGabor[0, 0] = 0. # Undo the radius fudge logGaborList.append(logGabor) # Matrix of radii cy = np.floor(rows / 2) cx = np.floor(cols / 2) y, x = np.mgrid[0:rows, 0:cols] y = (y - cy) / rows x = (x - cx) / cols radius = np.sqrt(x**2 + y**2) theta = np.arctan2(-y, x) radius = ifftshift( radius) # Quadrant shift radius and theta so that filters theta = ifftshift( theta) # are constructed with 0 frequency at the corners. radius[0, 0] = 1 sintheta = np.sin(theta) costheta = np.cos(theta) spreadList = [] for o in np.arange(norient): angl = o * np.pi / norient # Filter angle. ds = sintheta * math.cos(angl) - costheta * math.sin( angl) # Difference in sine. dc = costheta * math.cos(angl) + sintheta * math.sin( angl) # Difference in cosine. dtheta = np.abs(np.arctan2(ds, dc)) # Absolute angular distance. # dtheta = np.minimum(dtheta*NumberAngles/2, math.pi) spread = np.exp((-dtheta**2) / (2 * thetaSigma**2)) # Calculate the angular spreadList.append(spread) ifftFilterArray = [[], [], [], []] filterArray = [[], [], [], []] for o in np.arange(norient): for s in np.arange(nscale): filter = logGaborList[s] * spreadList[o] filterArray[o].append( torch.from_numpy(filter).reshape(1, 1, rows, cols).float().to(im.device)) ifftFilt = np.real(ifft2(filter)) * math.sqrt(rows * cols) ifftFilterArray[o].append( torch.from_numpy(ifftFilt).reshape(1, 1, rows, cols).float().to(im.device)) EnergyAll = 0 AnAll = 0 for o in np.arange(norient): sumE_ThisOrient = 0 sumO_ThisOrient = 0 sumAn_ThisOrient = 0 Energy = 0 MatrixEOList = [] for s in np.arange(nscale): filter = filterArray[o][s] c = imagefft * filter.unsqueeze(-1).repeat(1, 1, 1, 1, 2) MatrixEO = torch.ifft( imagefft * filter.unsqueeze(-1).repeat(1, 1, 1, 1, 2), 2) MatrixEOList.append(MatrixEO) An = abs(MatrixEO) # Amplitude of even & odd filter response. sumAn_ThisOrient = sumAn_ThisOrient + An # Sum of amplitude responses. sumE_ThisOrient = sumE_ThisOrient + real( MatrixEO) # Sum of even filter convolution results. sumO_ThisOrient = sumO_ThisOrient + imag( MatrixEO) # Sum of odd filter convolution results. if s == 0: EM_n = torch.sum(filter**2, dim=[1, 2, 3]) maxAn = An else: maxAn = torch.max(maxAn, An) XEnergy = torch.sqrt(sumE_ThisOrient**2 + sumO_ThisOrient**2 + 1e-12) + epsilon MeanE = sumE_ThisOrient / XEnergy MeanO = sumO_ThisOrient / XEnergy for s in np.arange(nscale): EO = MatrixEOList[s] E = real(EO) O = imag(EO) Energy = Energy + E * MeanE + O * MeanO - torch.abs(E * MeanO - O * MeanE) meanE2n = torch.median((abs(MatrixEOList[0])**2).view(im.shape[0], -1), dim=1)[0] / -math.log(0.5) noisePower = meanE2n / EM_n EstSumAn2 = 0 for s in np.arange(nscale): EstSumAn2 = EstSumAn2 + ifftFilterArray[o][s]**2 EstSumAiAj = 0 for si in np.arange(nscale - 1): for sj in np.arange(si + 1, nscale): EstSumAiAj = EstSumAiAj + ifftFilterArray[o][ si] * ifftFilterArray[o][sj] sumEstSumAn2 = torch.sum(EstSumAn2, dim=[1, 2, 3]) sumEstSumAiAj = torch.sum(EstSumAiAj, dim=[1, 2, 3]) EstNoiseEnergy2 = 2 * noisePower * sumEstSumAn2 + 4 * noisePower * sumEstSumAiAj tau = torch.sqrt(EstNoiseEnergy2 / 2 + 1e-12) EstNoiseEnergySigma = torch.sqrt((2 - math.pi / 2) * tau**2 + 1e-12) T = tau * math.sqrt(math.pi / 2) + k * EstNoiseEnergySigma T = T / 1.7 Energy = F.relu(Energy - T.view(-1, 1, 1, 1)) EnergyAll = EnergyAll + Energy AnAll = AnAll + sumAn_ThisOrient ResultPC = EnergyAll / AnAll return ResultPC
def compute_sampling_image(scene, antennas): if len(antennas) < 2: return False w = scene.interferometry.image_width h = scene.interferometry.image_height numpixels = w * h if w < 1 or h < 1: return False Bmax = 0.0 for i, a in enumerate(antennas): for b in antennas[i + 1:]: B = (b.xy - a.xy).length if B > Bmax: Bmax = B # bounds_min = antennas[0].xy # bounds_max = antennas[0].xy # for a in antennas[1:]: # if a.x < bounds_min.x: # bounds_min.x = a.x # if a.x > bounds_max.x: # bounds_max.x = a.x # if a.y < bounds_min.y: # bounds_min.y = a.y # if a.y > bounds_max.y: # bounds_max.y = a.y epsilon = 1.0e-6 scale = (min(w, h) / 4) / Bmax invscale = 1.0 / scale if scale > epsilon else 1.0 # Construct sampling from baselines # For real-valued output the input is complex conjugate # and irfft expects only the positive components. sampling = np.zeros((h, w), dtype=np.complex64) num_baselines = len(antennas) * (len(antennas) - 1) for i, a in enumerate(antennas): for b in antennas[i + 1:]: B = b.xy - a.xy s = B * scale # Symmetric sampling in the uv space sampling[int(h / 2 + 0.5 + s.y), int(w / 2 + 0.5 + s.x)] = 1.0 sampling[int(h / 2 + 0.5 - s.y), int(w / 2 + 0.5 - s.x)] = 1.0 # Compute point spread function fftin = fft.ifftshift(sampling) fftout = fft.ifft2(fftin) pointspread = fft.fftshift(fftout) * numpixels / num_baselines enqueue_image_pixel_update( sampling_queue, get_image=lambda scene: scene.interferometry.get_sampling_image(create= True), pixels=ndarray_to_pixels(sampling), width=sampling.shape[1], height=sampling.shape[0], allow_resize=True, ) enqueue_image_pixel_update( pointspread_queue, get_image=lambda scene: scene.interferometry.get_pointspread_image( create=True), pixels=ndarray_to_pixels(pointspread, mapping=(0.0, 1.0)), width=pointspread.shape[1], height=pointspread.shape[0], allow_resize=True, ) return True
IB_c.CentralDerivative_x(N, M, h, u, ux) IB_c.CentralDerivative_x(N, M, h, v, vx) IB_c.CentralDerivative_y(N, M, h, u, uy) IB_c.CentralDerivative_y(N, M, h, v, vy) fx, fy = ExplicitTerms(dt, u, v, ux, uy, vx, vy, 0., 0.) fx += dt * Current * ones((N, M), float64) fx = fft2(fx) fy = fft2(fy) P = Solve_P_Hat(dt, WideLambda, DxSymbol, DySymbol, fx, fy) P[0, 0] = 0. u, v = Solve_uv_Hat(dt, ShortLambda, DxSymbol, DySymbol, P, fx, fy) u = ifft2(u).real v = ifft2(v).real Xvel, Yvel = VelToFiber(N, M, h, Nb, hb, 1., X, Y, u, v) A = zeros((2 * Nb, 2 * Nb), float64) IB_c.ComputeMatrix(X, Y, _N, _M, Nb, _h, hb, UField, VField, UField2, VField2, A, -1) #, band = Nb/8+1) __A = [dt * A] for i in range(len(II)): print i __A.append( array(dot(transpose(II[i].todense()), dot(__A[i], II[i].todense()))))
# Initial guess using random phase info guess = diffract * np.exp(1j * np.random.rand(l, l) * 2 * pi) # number of iterations r = 801 # step size parameter beta = 0.8 # previous result prev = None for s in range(0, r): # apply fourier domain constraints update = diffract * np.exp(1j * np.angle(guess)) inv = fft.ifft2(update) # #======================= # # inv =np.abs(inv) #inv_imag = np.imag(inv) #print("inv_imag", inv_imag) # write fft process to txt # with open(save_path + "phase.txt","a") as rt: # rt.write(str(inv)) # print('inv',inv) inv = np.real(inv) if prev is None:
def solve_corr(bfek,N,I,g,beta,sigma_a,tslices,avals,avals_nl=[0,0,0]): # INPUT: # bfek <- compound kernel [K^2 a+KK*](assumed to be decentered) # N <- detector size (assumed odd for now) # I <- current # g <- gain (assuming no higher order fitting for now) # beta <- classical non-linearity # sigma_a <- sum of the BFE kernel # tslices <- list of time slices (ta, tb, tc, td) # avals <- list of alpha values for linear IPC kernel (aV, aH, aD) # avals_nl <- list of alpha values for NL-IPC kernel (aV_nl, aH_nl, aD_nl) # # OUTPUT: C_abcd ta, tb, tc, td = tslices aV, aH, aD = avals aV_nl, aH_nl, aD_nl = avals_nl if not bfek.shape[1]==bfek.shape[0]: warnings.warn("WARNING: convolved BFE kernel (BFEK) not square.") # Calculate K and K* from given alphas k = decenter(np.array([[aD,aV,aD], [aH,1-4*aD-2*aV-2*aH,aH], [aD,aV,aD]])) knl = decenter(np.array([[aD_nl,aV_nl,aD_nl], [aH_nl,1-4*aD_nl-2*aV_nl-2*aH_nl,aH_nl], [aD_nl,aV_nl,aD_nl]])) # solve Fourier version for asq: F(BFEK) = Ksq^2*asq + Ksq*Knl_sq ksq = fft2(pad_to_N(k,N)) knl_sq = fft2(pad_to_N(knl,N)) asq = (fft2(pad_to_N(bfek,N)) - ksq*knl_sq)/ksq**2 a = ifft2(asq) a_flipped = decenter(np.flip(center(a).flatten()).reshape(a.shape)) afsq = fft2(a_flipped) afsq_p = decenter(np.flip(center(afsq).flatten()).reshape(afsq.shape)) ksq_p = decenter(np.flip(center(ksq).flatten()).reshape(ksq.shape)) knl_sq_p = decenter(np.flip(center(knl_sq).flatten()).reshape(knl_sq.shape)) # Calculate Cov(qsq(t),qsq(t')) (see eqn 38) qqs = [] for ts in [(ta,tc),(ta,td),(tb,tc),(tb,td)]: t1 = min(ts) t = max(ts) qq = (1/(afsq+afsq_p+sigma_a) * np.exp(I*afsq*(t-t1)) * (np.exp(I*(afsq+afsq_p)*t1)-np.exp(I*sigma_a*t1))) qqs.append(qq) # Plug into correlation function (see eqn 51) csq_abcd =(1/g**2 *((1-2*beta*I*ta)*(1-2*beta*I*tc)*(ksq+knl_sq*I*ta)*(ksq_p+knl_sq_p*I*tc)*qqs[0] - (1-2*beta*I*ta)*(1-2*beta*I*td)*(ksq+knl_sq*I*ta)*(ksq_p+knl_sq_p*I*td)*qqs[1] - (1-2*beta*I*tb)*(1-2*beta*I*tc)*(ksq+knl_sq*I*tb)*(ksq_p+knl_sq_p*I*tc)*qqs[2] + (1-2*beta*I*tb)*(1-2*beta*I*td)*(ksq+knl_sq*I*tb)*(ksq_p+knl_sq_p*I*td)*qqs[3]) ) return np.real(ifft2(csq_abcd))
def prepare_DFT_solution(L,time,diffusivity, lambda_phi): # Mesh on the square [0,L)x[0,L) x = np.linspace(0, L-1, L) # columns (Width) y = np.linspace(0, L-1, L) # rows (Height) [X,Y] = np.meshgrid(x,y) xnorm = X / L * 2 * np.pi ynorm = Y / L * 4 * np.pi initial_condition = np.exp(np.sin(xnorm)) - 2*np.exp(np.sin(ynorm)) # initial_condition = np.cos(xnorm *0) plt.figure(figsize=(10, 10)) plt.imshow(initial_condition, cmap = 'gray') # coolwarm fig = plt.gcf() # get current figure plt.colorbar() plt.close(fig) F = fft2(initial_condition) ################ some tests... ################ ################ check FFT # Fshift = fftshift(F) # center it in the origin # Fshift = Fshift/(L*L) # normalize by the area # P = np.abs(Fshift) # # P = np.real(Fshift) # # P = np.imag(Fshift) # plt.figure(figsize=(10, 10)) # plt.imshow(P, extent = [-L,L,-L,L]); # fig = plt.gcf() # get current figure # plt.colorbar() # plt.close(fig) # ################ check inverse FFT # yinv = ifft2(F) # # P = np.abs(yinv) # P = np.real(yinv) # TODO: czemu to? # # P = np.imag(yinv) # plt.figure(figsize=(10, 10)) # plt.imshow(P, cmap = 'gray') # it is wise to check: P-initial_condition # fig = plt.gcf() # get current figure # plt.colorbar() # plt.close(fig) ################ end of tests... ################ n = L x2 = np.array([ float(i) if i < n/2 else float(-(n-i)) for i in range(0,n)]) k2, k1 = np.meshgrid(x2, x2) k1 *= 2.*np.pi/L k2 *= 2.*np.pi/L tmp = -time*(diffusivity*(k1**2+ k2**2 ) + lambda_phi) decay = np.exp(tmp) # https://stackoverflow.com/questions/40034993/how-to-get-element-wise-matrix-multiplication-hadamard-product-in-numpy # dummy_decay = np.ones(decay.shape) yinv = ifft2(np.multiply(F,decay)) # P = np.abs(yinv) P = np.real(yinv) # ignore imaginary artifacts # P = np.imag(yinv) # test with analytical solutions # k=1 # 2*np.pi*0.001 # tmp = -time*(diffusivity*(k**2) + lambda_phi) # P = np.cos(xnorm *k) * np.exp(tmp) plt.figure(figsize=(10, 10)) plt.imshow(P, cmap = 'gray') # it is wise to check: P-IC fig = plt.gcf() # get current figure plt.colorbar() plt.close(fig) return P
ATF = np.exp (1.j * weight * phase) # Amplitude Transfer Function z = 2*um # defocus distance angular_spectum_propagator = np.exp(1.j*2*np.pi*np.sqrt(k**2-k_rho**2)*z) #evanescent_idx = (k_rho >= k) #evanescent_idx = np.isnan(angular_spectum_propagator) #angular_spectum_propagator[evanescent_idx] = 0 # exclude all kx,ky that would be evanescent ATF = ATF * angular_spectum_propagator mask_idx = (k_rho > k_cut_off) ATF[mask_idx] = 0 # Creates a circular mask ASF = ifftshift(ifft2(ATF)) #* k**2/f**2 # Amplitude Spread Function PSF = np.abs(ASF)**2 # Point Spread Function # %%% plot the ATF and the PSF fig, ax = plt.subplots(1, 2, figsize=(9, 4), tight_layout=False) fig.suptitle(f'Wavefront aberrated with Zernike coefficient ({N},{M})') im0=ax[0].imshow(np.angle(ATF), #cmap='gray', extent = [np.amin(kx),np.amax(kx),np.amin(kx),np.amax(kx)], ) ax[0].set_xlabel('kx (1/$\mu$m)') ax[0].set_ylabel('ky (1/$\mu$m)') ax[0].set_title('ATF (phase)')
def __init__(self, I_image_up, xshift, yshift, N_bound_pad, lambda_f, pscrop, upsamp_factor, NA_obj, NAs, itr): # Basic parameter self.Nimg, self.N, self.M = I_image_up.shape self.N_bound_pad = N_bound_pad self.Nc = self.N + 2*N_bound_pad self.Mc = self.M + 2*N_bound_pad self.ps = pscrop/upsamp_factor self.itr = itr # Shift variable self.xshift = xshift self.yshift = yshift self.xshift_max = np.int(np.round(np.max(abs(xshift)))) self.yshift_max = np.int(np.round(np.max(abs(yshift)))) # Frequency grid definition to create TF fx_c = np.r_[-self.Mc/2:self.Mc/2]/self.ps/self.Mc fy_c = np.r_[-self.Nc/2:self.Nc/2]/self.ps/self.Nc fxx_c, fyy_c = np.meshgrid(fx_c,fy_c) fxx_c = ifftshift(fxx_c) fyy_c = ifftshift(fyy_c) Npp = self.Nc + 2*self.yshift_max Mpp = self.Mc + 2*self.xshift_max fxp = np.r_[-Mpp/2:Mpp/2]/self.ps/Mpp fyp = np.r_[-Npp/2:Npp/2]/self.ps/Npp fxxp, fyyp = np.meshgrid(fxp,fyp) self.fxxp = ifftshift(fxxp) self.fyyp = ifftshift(fyyp) # Initialization of object and pattern self.I_obj = np.pad(np.mean(I_image_up,axis=0),(N_bound_pad,),mode='constant') self.I_p_whole = np.ones((Npp, Mpp)) # Compute transfer function Pupil_obj = np.zeros((self.Nc,self.Mc)) frc = (fxx_c**2 + fyy_c**2)**(1/2) Pupil_obj[frc<NA_obj/lambda_f] = 1 T_incoherent = abs(fft2(abs(ifft2(Pupil_obj))**2)) self.T_incoherent = T_incoherent/np.max(T_incoherent) # Compute support function self.Pattern_support = np.zeros((Npp,Mpp)) frp = (self.fxxp**2 + self.fyyp**2)**(1/2) self.Pattern_support[frp<2*NAs/lambda_f] = 1 self.Object_support = np.zeros((self.Nc,self.Mc)) self.Object_support[frc<2*(NA_obj+NAs)/lambda_f] = 1 self.OTF_support = np.zeros((self.Nc,self.Mc)) self.OTF_support[frc<2*NA_obj/lambda_f] = 1 # iteration error self.err = np.zeros(self.itr+1)
P,Q=image.shape #F(u,v)---fourier transform of image(x,y) F=fp.fft2(image) F=fp.fftshift(F) print("fourier transform",F) H=np.zeros([P,Q]) print(H.shape) D0=int(input('Enter the cut-off frequency- ')) for i in range(P): for j in range(Q): dist=math.sqrt(math.pow((i-P/2),2)+math.pow((j-Q/2),2)) k=math.pow(dist,2)/math.pow(D0,2) H[i][j]=1-math.exp(-0.50000000000*k) filter=np.clip(H,0,255) plt.subplot(222),plt.imshow(filter,cmap='gray') G = [ [ 0+0j for i in range(Q) ] for j in range(P) ] for i in range(P): for j in range(Q): G[i][j]=H[i][j]*F[i][j] # print("printing G",G) g=fp.ifft2(fp.ifftshift(G)).real I5=np.log10(np.abs(G)) plt.subplot(223),plt.imshow(I5,cmap='gray') plt.subplot(224),plt.imshow(g,cmap='gray');plt.show() # print(count,H)
def __execute_basket_weaving(self): ### # Basket-Weaving (Emerson & Grave 1988) ### casalog.post('Apply Basket-Weaving') # CAS-5410 Use private tools inside task scripts ia = gentools(['ia'])[0] # initial setup outimage = ia.newimagefromimage(infile=self.infiles[0], outfile=self.outfile, overwrite=self.overwrite) imshape_out = outimage.shape() ndim_out = len(imshape_out) coordsys = outimage.coordsys() axis_types = coordsys.axiscoordinatetypes() # direction axis should always exist try: direction_axis0 = axis_types.index('Direction') direction_axis1 = axis_types[direction_axis0 + 1:].index( 'Direction') + direction_axis0 + 1 except IndexError: raise RuntimeError('Direction axes don\'t exist.') nx = imshape_out[direction_axis0] ny = imshape_out[direction_axis1] tmp = [] nfile = len(self.infiles) for i in xrange(nfile): tmp.append(numpy.zeros(imshape_out, dtype=float)) maskedpixel = numpy.array(tmp) del tmp # direction dirs = [] if len(self.direction) == nfile: dirs = self.direction else: casalog.post('direction information is extrapolated.') for i in range(nfile): dirs.append(self.direction[i % len(self.direction)]) # maskwidth masks = [] if isinstance(self.maskwidth, int) or isinstance( self.maskwidth, float): for i in range(nfile): masks.append(self.maskwidth) elif isinstance(self.maskwidth, list): # and nfile != len(self.maskwidth): for i in range(nfile): masks.append(self.maskwidth[i % len(self.maskwidth)]) for i in range(len(masks)): masks[i] = 0.01 * masks[i] # mask for i in range(nfile): self.realimage = create_4d_image(self.infiles[i], self.tmprealname[i]) self.imagimage = self.realimage.subimage( outfile=self.tmpimagname[i]) # replace masked pixels with 0.0 if not self.realimage.getchunk(getmask=True).all(): casalog.post( "Replacing masked pixels with 0.0 in %d-th image" % (i)) self.realimage.replacemaskedpixels(0.0) self.realimage.close() self.imagimage.close() # Below working images are all 4D regardless of dimension of input images # image shape for temporary images (always 4D) ia.open(self.tmprealname[0]) imshape = ia.shape() ndim = len(imshape) ia.close() if len(self.thresh) == 0: casalog.post('Use whole region') else: for i in range(nfile): self.realimage = ia.newimage(self.tmprealname[i]) for iaxis2 in range(imshape[2]): for iaxis3 in range(imshape[3]): pixmsk = self.realimage.getchunk( [0, 0, iaxis2, iaxis3], [nx - 1, ny - 1, iaxis2, iaxis3]) for ix in range(pixmsk.shape[0]): for iy in range(pixmsk.shape[1]): if self.thresh[0] == self.nolimit: if pixmsk[ix][iy] > self.thresh[1]: maskedpixel[i][ix][iy][iaxis2][ iaxis3] = pixmsk[ix][iy] pixmsk[ix][iy] = 0.0 elif self.thresh[1] == self.nolimit: if pixmsk[ix][iy] < self.thresh[0]: maskedpixel[i][ix][iy][iaxis2][ iaxis3] = pixmsk[ix][iy] pixmsk[ix][iy] = 0.0 else: if pixmsk[ix][iy] < self.thresh[ 0] or pixmsk[ix][iy] > self.thresh[ 1]: maskedpixel[i][ix][iy][iaxis2][ iaxis3] = pixmsk[ix][iy] pixmsk[ix][iy] = 0.0 self.realimage.putchunk(pixmsk, [0, 0, iaxis2, iaxis3]) self.realimage.close() maskedvalue = None if any(maskedpixel.flatten() != 0.0): maskedvalue = maskedpixel.mean(axis=0) del maskedpixel # set weight factor weights = numpy.ones(shape=(nfile, nx, ny), dtype=float) eps = 1.0e-5 dtor = numpy.pi / 180.0 for i in range(nfile): scan_direction = '' if abs(numpy.sin( dirs[i] * dtor)) < eps: # direction is around 0 deg maskw = 0.5 * nx * masks[i] scan_direction = 'horizontal' elif abs(numpy.cos( dirs[i] * dtor)) < eps: # direction is around 90 deg maskw = 0.5 * ny * masks[i] scan_direction = 'vertical' else: maskw = 0.5 * numpy.sqrt(nx * ny) * masks[i] for ix in range(nx): halfwx = (nx - 1) / 2 for iy in range(ny): halfwy = (ny - 1) / 2 if scan_direction == 'horizontal': #dd = abs(float(ix) - 0.5*(nx-1)) dd = abs(float(ix) - halfwx) # for CAS-9434 elif scan_direction == 'vertical': #dd = abs(float(iy) - 0.5*(ny-1)) dd = abs(float(iy) - halfwy) # for CAS-9434 else: tand = numpy.tan((dirs[i] - 90.0) * dtor) #dd = abs((float(ix) - 0.5*(nx-1)) * tand - (float(iy) - 0.5*(ny-1))) dd = abs((float(ix) - halfwx) * tand - (float(iy) - halfwy)) # for CAS-9434 dd = dd / numpy.sqrt(1.0 + tand * tand) if dd < maskw: cosd = numpy.cos(0.5 * numpy.pi * dd / maskw) weights[i][ix][iy] = 1.0 - cosd * cosd if weights[i][ix][iy] == 0.0: weights[i][ix][iy] += eps * 0.01 """ if abs(numpy.sin(dirs[i]*dtor)) < eps: # direction is around 0 deg maskw = 0.5 * nx * masks[i] for ix in range(nx): for iy in range(ny): dd = abs( float(ix) - 0.5 * (nx-1) ) if dd < maskw: cosd = numpy.cos(0.5*numpy.pi*dd/maskw) weights[i][ix][iy] = 1.0 - cosd * cosd if weights[i][ix][iy] == 0.0: weights[i][ix][iy] += eps*0.01 elif abs(numpy.cos(dirs[i]*dtor)) < eps: # direction is around 90 deg maskw = 0.5 * ny * masks[i] for ix in range(nx): for iy in range(ny): dd = abs( float(iy) - 0.5 * (ny-1) ) if dd < maskw: cosd = numpy.cos(0.5*numpy.pi*dd/maskw) weights[i][ix][iy] = 1.0 - cosd * cosd if weights[i][ix][iy] == 0.0: weights[i][ix][iy] += eps*0.01 else: maskw = 0.5 * numpy.sqrt( nx * ny ) * masks[i] for ix in range(nx): for iy in range(ny): tand = numpy.tan((dirs[i]-90.0)*dtor) dd = abs( ix * tand - iy - 0.5 * (nx-1) * tand + 0.5 * (ny-1) ) dd = dd / numpy.sqrt( 1.0 + tand * tand ) if dd < maskw: cosd = numpy.cos(0.5*numpy.pi*dd/maskw) weights[i][ix][iy] = 1.0 - cosd * cosd if weights[i][ix][iy] == 0.0: weights[i][ix][iy] += eps*0.01 """ # shift xshift = -((ny - 1) / 2) yshift = -((nx - 1) / 2) for ix in range(xshift, 0, 1): tmp = weights[i, :, 0].copy() weights[i, :, 0:ny - 1] = weights[i, :, 1:ny].copy() weights[i, :, ny - 1] = tmp for iy in range(yshift, 0, 1): tmp = weights[i, 0:1].copy() weights[i, 0:nx - 1] = weights[i, 1:nx].copy() weights[i, nx - 1:nx] = tmp # FFT for i in range(nfile): self.realimage = ia.newimage(self.tmprealname[i]) self.imagimage = ia.newimage(self.tmpimagname[i]) for iaxis2 in range(imshape[2]): for iaxis3 in range(imshape[3]): pixval = self.realimage.getchunk( [0, 0, iaxis2, iaxis3], [nx - 1, ny - 1, iaxis2, iaxis3]) pixval = pixval.reshape((nx, ny)) pixfft = npfft.fft2(pixval) pixfft = pixfft.reshape((nx, ny, 1, 1)) self.realimage.putchunk(pixfft.real, [0, 0, iaxis2, iaxis3]) self.imagimage.putchunk(pixfft.imag, [0, 0, iaxis2, iaxis3]) del pixval, pixfft self.realimage.close() self.imagimage.close() # weighted mean for ichan in range(imshape[2]): for iaxis3 in range(imshape[3]): pixout = numpy.zeros(shape=(nx, ny), dtype=complex) denom = numpy.zeros(shape=(nx, ny), dtype=float) for i in range(nfile): self.realimage = ia.newimage(self.tmprealname[i]) self.imagimage = ia.newimage(self.tmpimagname[i]) pixval = self.realimage.getchunk( [0,0,ichan,iaxis3], [nx-1,ny-1,ichan,iaxis3] ) \ + self.imagimage.getchunk( [0,0,ichan,iaxis3], [nx-1,ny-1,ichan,iaxis3] ) * 1.0j pixval = pixval.reshape((nx, ny)) pixout = pixout + pixval * weights[i] denom = denom + weights[i] self.realimage.close() self.imagimage.close() pixout = pixout / denom pixout = pixout.reshape((nx, ny, 1, 1)) self.realimage = ia.newimage(self.tmprealname[0]) self.imagimage = ia.newimage(self.tmpimagname[0]) self.realimage.putchunk(pixout.real, [0, 0, ichan, iaxis3]) self.imagimage.putchunk(pixout.imag, [0, 0, ichan, iaxis3]) self.realimage.close() self.imagimage.close() # inverse FFT self.realimage = ia.newimage(self.tmprealname[0]) self.imagimage = ia.newimage(self.tmpimagname[0]) for ichan in range(imshape[2]): for iaxis3 in range(imshape[3]): pixval = self.realimage.getchunk( [0,0,ichan,iaxis3], [nx-1,ny-1,ichan,iaxis3] ) \ + self.imagimage.getchunk( [0,0,ichan,iaxis3], [nx-1,ny-1,ichan,iaxis3] ) * 1.0j pixval = pixval.reshape((nx, ny)) pixifft = npfft.ifft2(pixval) pixifft = pixifft.reshape((nx, ny, 1, 1)) self.realimage.putchunk(pixifft.real, blc=[0, 0, ichan, iaxis3]) del pixval, pixifft if maskedvalue is not None: self.realimage.putchunk(self.realimage.getchunk() + maskedvalue) # put result into outimage chunk = self.realimage.getchunk() outimage.putchunk(chunk.reshape(imshape_out)) # handling of output image mask maskstr = "" for name in self.infiles: if len(maskstr) > 0: maskstr += " || " maskstr += ("mask('%s')" % (name)) outimage.calcmask(maskstr, name="basketweaving", asdefault=True) self.realimage.close() self.imagimage.close() outimage.close()
angle=180, ledmat_shape=[npx, npx], radius=radius) S3 = fpm.create_source_pattern(shape='semicircle', angle=90, ledmat_shape=[npx, npx], radius=radius) S4 = fpm.create_source_pattern(shape='semicircle', angle=270, ledmat_shape=[npx, npx], radius=radius) Hph1 = create_hph(angle1=0, angle2=180, npx=200, radius=radius) Hph2 = create_hph(angle1=90, angle2=270, npx=200, radius=radius) I1 = np.abs(ifft2(S1 * image_fft)) I2 = np.abs(ifft2(S2 * image_fft)) I3 = np.abs(ifft2(S3 * image_fft)) I4 = np.abs(ifft2(S4 * image_fft)) Idpc1 = simple_dpc(I1, I2) Idpc2 = simple_dpc(I3, I4) # phi = tik_deconvolution([Hph1], [Idpc1], alpha=0.1) print(Idpc1.shape, np.zeros(shape=(npx, 1)).shape) A1 = np.concatenate((Hph1, 1 * np.matlib.identity(npx))) b1 = np.concatenate((Idpc1, np.zeros(shape=(1, npx)))) phi = optimize.nnls(A1, b1) fig, (axes) = plt.subplots(3, 2, figsize=(25, 15))
def iterative_algorithm(self, I_image_up, update_shift=1, shift_alpha=1, update_OTF=0, OTF_alpha=1, figsize=(15,5)): f1,ax = plt.subplots(1,3,figsize=figsize) tic_time = time.time() print('| Iter | error | Elapsed time (sec) |') for i in range(0,self.itr): # sequential update for j in range(0,self.Nimg): Ip_shift = np.maximum(0, np.real(ifft2(fft2(self.I_p_whole) * \ np.exp(1j*2*np.pi*self.ps*(self.fxxp * self.xshift[j] + self.fyyp * self.yshift[j]))))) I_p = Ip_shift[self.yshift_max:self.Nc+self.yshift_max, self.xshift_max:self.Mc+self.xshift_max] I_image_current = I_image_up[j] I_multi_f = fft2(I_p * self.I_obj) I_est = ifft2(self.T_incoherent * I_multi_f) I_diff = I_image_current - I_est[self.N_bound_pad:self.N_bound_pad+self.N, self.N_bound_pad:self.N_bound_pad+self.M] I_temp = ifft2(self.T_incoherent * fft2(np.pad(I_diff,(self.N_bound_pad,),mode='constant'))) # gradient computation grad_Iobj = -np.real(I_p * I_temp) grad_Ip = -np.real(ifft2(fft2(np.pad(self.I_obj * I_temp,((self.yshift_max,),(self.xshift_max,)), mode='constant'))\ * np.exp(-1j*2*np.pi*self.ps*(self.fxxp * self.xshift[j] + self.fyyp * self.yshift[j])))) if update_OTF ==1: grad_OTF = -np.conj(I_multi_f) * fft2(I_temp) # updating equation self.I_obj = np.real(ifft2(fft2(self.I_obj - grad_Iobj/(np.max(I_p)**2)) * self.Object_support)) self.I_p_whole = np.real(ifft2(fft2(self.I_p_whole - grad_Ip/(np.max(self.I_obj)**2)) * self.Pattern_support)) if update_OTF ==1: self.T_incoherent = (self.T_incoherent - grad_OTF/np.max(abs(I_multi_f)) * \ abs(I_multi_f) / (abs(I_multi_f)**2 + 1e-3) * OTF_alpha * self.OTF_support).copy() # shift estimate if update_shift ==1: Ip_shift_fx = ifft2(fft2(self.I_p_whole) * (1j*2*np.pi*self.fxxp) * \ np.exp(1j*2*np.pi*self.ps*(self.fxxp * self.xshift[j] + self.fyyp * self.yshift[j]))) Ip_shift_fy = ifft2(fft2(self.I_p_whole) * (1j*2*np.pi*self.fyyp) * \ np.exp(1j*2*np.pi*self.ps*(self.fxxp * self.xshift[j] + self.fyyp * self.yshift[j]))) Ip_shift_fx = Ip_shift_fx[self.yshift_max:self.yshift_max+self.Nc,self.xshift_max:self.xshift_max+self.Mc] Ip_shift_fy = Ip_shift_fy[self.yshift_max:self.yshift_max+self.Nc,self.xshift_max:self.xshift_max+self.Mc] grad_xshift = -np.real(np.sum(np.conj(I_temp) * self.I_obj * Ip_shift_fx)) grad_yshift = -np.real(np.sum(np.conj(I_temp) * self.I_obj * Ip_shift_fy)) self.xshift[j] = self.xshift[j] - grad_xshift/self.N/self.M/(np.max(self.I_obj)**2) * shift_alpha self.yshift[j] = self.yshift[j] - grad_yshift/self.N/self.M/(np.max(self.I_obj)**2) * shift_alpha self.err[i+1] += np.sum(abs(I_diff)**2) # Nesterov acceleration temp = self.I_obj.copy() temp_Ip = self.I_p_whole.copy() if i == 0: t = 1 self.I_obj = temp.copy() tempp = temp.copy() self.I_p_whole = temp_Ip.copy() tempp_Ip = temp_Ip.copy() else: if self.err[i] >= self.err[i-1]: t = 1 self.I_obj = temp.copy() tempp = temp.copy() self.I_p_whole = temp_Ip.copy() tempp_Ip = temp_Ip.copy() else: tp = t t = (1 + (1 + 4 * tp**2)**(1/2))/2 self.I_obj = temp + (tp - 1) * (temp - tempp) / t tempp = temp.copy() self.I_p_whole = temp_Ip + (tp - 1) * (temp_Ip - tempp_Ip) / t tempp_Ip = temp_Ip.copy() if np.mod(i,1) == 0: print('| %d | %.2e | %.2f |'%(i+1,self.err[i+1],time.time()-tic_time)) if i != 1: ax[0].cla() ax[1].cla() ax[2].cla() ax[0].imshow(np.maximum(0,self.I_obj),cmap='gray'); ax[1].imshow(np.maximum(0,self.I_p_whole),cmap='gray') ax[2].plot(self.xshift,self.yshift,'w') display.display(f1) display.clear_output(wait=True) time.sleep(0.0001) if i == self.itr-1: print('| %d | %.2e | %.2f |'%(i+1,self.err[i+1],time.time()-tic_time))
def make_blurred(input, PSF, eps): input_fft = fft.fft2(input) # 进行二维数组的傅里叶变换 PSF_fft = fft.fft2(PSF) + eps blurred = fft.ifft2(input_fft * PSF_fft) blurred = np.abs(fft.fftshift(blurred)) return blurred
def similarity(im0, im1): """Return similarity transformed image im1 and transformation parameters. Transformation parameters are: isotropic scale factor, rotation angle (in degrees), and translation vector. A similarity transformation is an affine transformation with isotropic scale and without shear. Limitations: Image shapes must be equal and square. All image areas must have same scale, rotation, and shift. Scale change must be less than 1.8. No subpixel precision. """ if im0.shape != im1.shape: raise ValueError("Images must have same shapes.") elif len(im0.shape) != 2: raise ValueError("Images must be 2 dimensional.") f0 = fftshift(abs(fft2(im0))) f1 = fftshift(abs(fft2(im1))) h = highpass(f0.shape) f0 *= h f1 *= h del h f0, log_base = logpolar(f0) f1, log_base = logpolar(f1) f0 = fft2(f0) f1 = fft2(f1) r0 = abs(f0) * abs(f1) ir = abs(ifft2((f0 * f1.conjugate()) / r0)) i0, i1 = numpy.unravel_index(numpy.argmax(ir), ir.shape) angle = 180.0 * i0 / ir.shape[0] scale = log_base**i1 if scale > 1.8: ir = abs(ifft2((f1 * f0.conjugate()) / r0)) i0, i1 = numpy.unravel_index(numpy.argmax(ir), ir.shape) angle = -180.0 * i0 / ir.shape[0] scale = 1.0 / (log_base**i1) if scale > 1.8: raise ValueError("Images are not compatible. Scale change > 1.8") if angle < -90.0: angle += 180.0 elif angle > 90.0: angle -= 180.0 im2 = ndii.zoom(im1, 1.0 / scale) im2 = ndii.rotate(im2, angle) if im2.shape < im0.shape: t = numpy.zeros_like(im0) t[:im2.shape[0], :im2.shape[1]] = im2 im2 = t elif im2.shape > im0.shape: im2 = im2[:im0.shape[0], :im0.shape[1]] f0 = fft2(im0) f1 = fft2(im2) ir = abs(ifft2((f0 * f1.conjugate()) / (abs(f0) * abs(f1)))) t0, t1 = numpy.unravel_index(numpy.argmax(ir), ir.shape) if t0 > f0.shape[0] // 2: t0 -= f0.shape[0] if t1 > f0.shape[1] // 2: t1 -= f0.shape[1] im2 = ndii.shift(im2, [t0, t1]) # correct parameters for ndimage's internal processing if angle > 0.0: d = int((int(im1.shape[1] / scale) * math.sin(math.radians(angle)))) t0, t1 = t1, d + t0 elif angle < 0.0: d = int((int(im1.shape[0] / scale) * math.sin(math.radians(angle)))) t0, t1 = d + t1, d + t0 scale = (im1.shape[1] - 1) / (int(im1.shape[1] / scale) - 1) return im2, scale, angle, [-t0, -t1]
Enstrophy.append(0.5 * mean(mean((Rgsq-F*Rwsq)**2))) umax = abs(dwdy).max() vmax = abs(dwdx).max() maxx=array((umax,vmax)) VMAX = maxx.max() Q_np1 = Q_nm1 - (2*Dt)*((grav/fcor0)*Jacobi + beta0*dwdx + Ubar*dlapdx) #Section 3.3: Solve the Helmholtz Equation (Del^2-F)w = R.Compute the fft of the #right hand side (strip off additional row and column). R[0:nx,0:ny] = Q_np1[0:nx,0:ny] R_hat = fft2(R) #Compute the transform of the solution W_hat = R_hat/C_rs #Compute the inverse transform to get the solution at (n+1)*Delta_t. w_new = real(ifft2(W_hat)) # We assume w is real w[0:nx,0:ny] = w_new w[nx,0:ny] = w[0,0:ny] # Fill in additional column at east. w[0:nx+1,ny]=w[0:nx+1,0] # Fill in additional row at north. #Add the term for the zonal mean flow. wtotal = w + Hbar - (fcor0/grav)*Ubar*YY zonalwind.append(-grav*dwdy/fcor0) #Save an east-west mid cross-section each time-step #w_section[0:nx+1,n-1] = w[0:nx+1,int(fix(ny/2))] #Shuffle the fields at the end of each time-step Dt = Delta_t Q_nm1 = Q_n timeestep=n
def filterDFourierTransform(imageMatrix, filteredMatrix): shiftedDFT = fftshift(fft2(imageMatrix)) filteredDFT = shiftedDFT * filteredMatrix return ifft2(ifftshift(filteredDFT))
npx = 32 radius = 10 mag_array = misc.imread('sandbox/alambre.png', 'F')[:npx, :npx] image_phase = misc.imread('sandbox/lines0_0.png', 'F')[:npx, :npx] ph_array = np.pi * (image_phase) / np.amax(image_phase) image_array = mag_array * np.exp(1j * ph_array) image_fft = fftshift(fft2(image_array)) angles = [0, 180, 90, 270, 45, 225, 135, 315] pupil_list = [] image_list = [] for angle in angles: H = (fpm.create_source_pattern(shape='semicircle', angle=angle, ledmat_shape=[npx, npx], radius=radius, int_radius=20)) pupil_list.append(H) image_list.append(np.abs(ifft2(H * image_fft))) fig, (axes) = plt.subplots(2, 2, figsize=(25, 15)) fig.show() # IDPC2 = np.abs(ifft2(H2*image_fft)) axes[0][0].imshow(pupil_list[0] + pupil_list[2]) axes[0][1].imshow(pupil_list[1] + pupil_list[3]) signal.correlate2d(in1, in2, mode='full', boundary='fill', fillvalue=0) plt.show()
def invert(self, FT_image, full=False): if full: return ifft2(ifftshift(FT_image)) else: return ifft2(ifftshift(FT_image)).real
import numpy as np from numpy import pi from numpy.fft import fft2 from numpy.fft import ifft2 from numpy.fft import fftshift from numpy.fft import ifftshift import matplotlib.pyplot as plt from skimage.data import shepp_logan_phantom from skimage.transform import resize FFT = lambda x: fftshift(fft2(ifftshift(x))) IFFT = lambda x: fftshift(ifft2(ifftshift(x))) EPS = 1e-18 ## 3) Shift in Fourier domain # exp(j*2pi*a*x) * f(x) <== Fourier Transform ==> FFT(f(x))(kx - a) N = 512 X = shepp_logan_phantom() X = resize(X, (N, N), order=0) X_fft = FFT(X) nx = np.linspace(1, N, N) ny = np.linspace(1, N, N) [mx, my] = np.meshgrid(nx, ny) dx = 100 dy = 100
football = cv2.imread("noiseball.png", 0) H, W = np.shape(football) hW = W // 2 hH = H // 2 PQ = paddedsize(np.array(np.shape(football))) H1 = notch('gaussian', PQ[0], PQ[1], 10, 50, 100, 1) H2 = notch('gaussian', PQ[0], PQ[1], 10, 0, 400, 1) H3 = notch('gaussian', PQ[0], PQ[1], 10, 620, 100, 1) H4 = notch('gaussian', PQ[0], PQ[1], 10, 22, 414, 1) H5 = notch('gaussian', PQ[0], PQ[1], 10, 592, 414, 1) H6 = notch('gaussian', PQ[0], PQ[1], 10, 0, 114, 1) F = fft2((football), s=[2 * H, 2 * W]) / (H * W) F_ifft = F * H1 * H2 * H3 * H4 * H5 * H6 F_football = ifft2(F_ifft) F_football = F_football[:H, :W] F = fftshift(F) F_ifft = fftshift(F_ifft) S1 = np.log(1 + np.abs(F)) S2 = np.log(1 + np.abs(F_ifft)) images = [football, np.abs(F_football), S1, S2] title = [ 'Anh co nhieu', 'Anh da loc nhieu', 'Pho anh co nhieu', 'Pho anh loc nhieu' ] r = 150 for i in range(4): if i < 2: plt.subplot(2, 2, i + 1), plt.imshow(images[i], cmap='gray') else:
def telescopeOtf(pupil, samp): pup_pad = enlargeSupport(pupil, samp) otf = fft.fftshift(fft.ifft2(fft.fft2(fft.fftshift(pup_pad))**2)) return otf / otf.max()
import numpy as np N = 100 px = 0.5 #arcmin trueArea = (N*px)**2. print(("true area ", trueArea , " arcmin^2")) mat = np.ones((N,N)) easyArea = np.sum(mat)*px**2. print(("easy area ", easyArea , " arcmin^2")) from numpy.fft import fft2,ifft2 ft = fft2(mat) diffArea = ifft2(ft*ft).real * px**2. #/ N/N print(("difficult area ", diffArea , " arcmin^2"))
def __execute_basket_weaving(self): ### # Basket-Weaving (Emerson & Grave 1988) ### casalog.post('Apply Basket-Weaving') # CAS-5410 Use private tools inside task scripts ia = gentools(['ia'])[0] # initial setup outimage = ia.newimagefromimage(infile=self.infiles[0], outfile=self.outfile, overwrite=self.overwrite) imshape = outimage.shape() nx = imshape[0] ny = imshape[1] nchan = imshape[2] tmp = [] nfile = len(self.infiles) for i in xrange(nfile): tmp.append(numpy.zeros(imshape, dtype=float)) maskedpixel = numpy.array(tmp) del tmp # direction dirs = [] if len(self.direction) == nfile: dirs = self.direction else: casalog.post('direction information is extrapolated.') for i in range(nfile): dirs.append(self.direction[i % len(direction)]) # masklist masks = [] if type(self.masklist) == float: for i in range(nfile): masks.append(self.masklist) elif type(self.masklist) == list and nfile != len(self.masklist): for i in range(nfile): masks.append(self.masklist[i % len(self.masklist)]) for i in range(len(masks)): masks[i] = 0.01 * masks[i] # mask for i in range(nfile): self.realimage = ia.newimagefromimage(infile=self.infiles[i], outfile=self.tmprealname[i]) self.imagimage = ia.newimagefromimage(infile=self.infiles[i], outfile=self.tmpimagname[i]) # replace masked pixels with 0.0 if not self.realimage.getchunk(getmask=True).all(): casalog.post( "Replacing masked pixels with 0.0 in %d-th image" % (i)) self.realimage.replacemaskedpixels(0.0) self.realimage.close() self.imagimage.close() if len(self.thresh) == 0: casalog.post('Use whole region') else: if len(imshape) == 4: # with polarization axis npol = imshape[3] for i in range(nfile): self.realimage = ia.newimage(self.tmprealname[i]) for ichan in range(nchan): for ipol in range(npol): pixmsk = self.realimage.getchunk( [0, 0, ichan, ipol], [nx - 1, ny - 1, ichan, ipol]) for ix in range(pixmsk.shape[0]): for iy in range(pixmsk.shape[1]): if self.thresh[0] == self.nolimit: if pixmsk[ix][iy] > self.thresh[1]: maskedpixel[i][ix][iy][ichan][ ipol] = pixmsk[ix][iy] pixmsk[ix][iy] = 0.0 elif self.thresh[1] == self.nolimit: if pixmsk[ix][iy] < self.thresh[0]: maskedpixel[i][ix][iy][ichan][ ipol] = pixmsk[ix][iy] pixmsk[ix][iy] = 0.0 else: if pixmsk[ix][iy] < self.thresh[ 0] or pixmsk[ix][ iy] > self.thresh[1]: maskedpixel[i][ix][iy][ichan][ ipol] = pixmsk[ix][iy] pixmsk[ix][iy] = 0.0 self.realimage.putchunk(pixmsk, [0, 0, ichan, ipol]) self.realimage.close() elif len(imshape) == 3: # no polarization axis for i in range(nfile): self.realimage = ia.newimage(self.tmprealname[i]) for ichan in range(nchan): pixmsk = self.realimage.getchunk( [0, 0, ichan], [nx - 1, ny - 1, ichan]) for ix in range(pixmsk.shape[0]): for iy in range(pixmsk.shape[1]): if self.thresh[0] == self.nolimit: if pixmsk[ix][iy] > self.thresh[1]: maskedpixel[i][ix][iy][ichan] = pixmsk[ ix][iy] pixmsk[ix][iy] = 0.0 elif self.thresh[1] == self.nolimit: if pixmsk[ix][iy] < self.thresh[0]: maskedpixel[i][ix][iy][ichan] = pixmsk[ ix][iy] pixmsk[ix][iy] = 0.0 else: if pixmsk[ix][iy] < self.thresh[ 0] or pixmsk[ix][iy] > self.thresh[ 1]: maskedpixel[i][ix][iy][ichan] = pixmsk[ ix][iy] pixmsk[ix][iy] = 0.0 self.realimage.putchunk(pixmsk, [0, 0, ichan]) self.realimage.close() maskedvalue = None if any(maskedpixel.flatten() != 0.0): maskedvalue = maskedpixel.mean(axis=0) del maskedpixel # set weight factor weights = numpy.ones(shape=(nfile, nx, ny), dtype=float) eps = 1.0e-5 dtor = numpy.pi / 180.0 for i in range(nfile): if abs(numpy.sin(dirs[i] * dtor)) < eps: # direction is around 0 deg maskw = 0.5 * nx * masks[i] for ix in range(nx): for iy in range(ny): dd = abs(float(ix) - 0.5 * (nx - 1)) if dd < maskw: cosd = numpy.cos(0.5 * numpy.pi * dd / maskw) weights[i][ix][iy] = 1.0 - cosd * cosd if weights[i][ix][iy] == 0.0: weights[i][ix][iy] += eps * 0.01 elif abs(numpy.cos(dirs[i] * dtor)) < eps: # direction is around 90 deg maskw = 0.5 * ny * masks[i] for ix in range(nx): for iy in range(ny): dd = abs(float(iy) - 0.5 * (ny - 1)) if dd < maskw: cosd = numpy.cos(0.5 * numpy.pi * dd / maskw) weights[i][ix][iy] = 1.0 - cosd * cosd if weights[i][ix][iy] == 0.0: weights[i][ix][iy] += eps * 0.01 else: maskw = 0.5 * sqrt(nx * ny) * masks[i] for ix in range(nx): for iy in range(ny): tand = numpy.tan((dirs[i] - 90.0) * dtor) dd = abs(ix * tand - iy - 0.5 * (nx - 1) * tand + 0.5 * (ny - 1)) dd = dd / sqrt(1.0 + tand * tand) if dd < maskw: cosd = numpy.cos(0.5 * numpy.pi * dd / maskw) weights[i][ix][iy] = 1.0 - cosd * cosd if weights[i][ix][iy] == 0.0: weights[i][ix][iy] += eps * 0.01 # shift xshift = -((ny - 1) / 2) yshift = -((nx - 1) / 2) for ix in range(xshift, 0, 1): tmp = weights[i, :, 0].copy() weights[i, :, 0:ny - 1] = weights[i, :, 1:ny].copy() weights[i, :, ny - 1] = tmp for iy in range(yshift, 0, 1): tmp = weights[i, 0:1].copy() weights[i, 0:nx - 1] = weights[i, 1:nx].copy() weights[i, nx - 1:nx] = tmp # FFT if len(imshape) == 4: # with polarization axis npol = imshape[3] for i in range(nfile): self.realimage = ia.newimage(self.tmprealname[i]) self.imagimage = ia.newimage(self.tmpimagname[i]) for ichan in range(nchan): for ipol in range(npol): pixval = self.realimage.getchunk( [0, 0, ichan, ipol], [nx - 1, ny - 1, ichan, ipol]) pixval = pixval.reshape((nx, ny)) pixfft = npfft.fft2(pixval) pixfft = pixfft.reshape((nx, ny, 1, 1)) self.realimage.putchunk(pixfft.real, [0, 0, ichan, ipol]) self.imagimage.putchunk(pixfft.imag, [0, 0, ichan, ipol]) del pixval, pixfft self.realimage.close() self.imagimage.close() elif len(imshape) == 3: # no polarization axis for i in range(nfile): self.realimage = ia.newimage(self.tmprealname[i]) self.imagimage = ia.newimage(self.tmpimagname[i]) for ichan in range(nchan): pixval = self.realimage.getchunk([0, 0, ichan], [nx - 1, ny - 1, ichan]) pixval = pixval.reshape((nx, ny)) pixfft = npfft.fft2(pixval) pixfft = pixfft.reshape((nx, ny, 1)) self.realimage.putchunk(pixfft.real, [0, 0, ichan]) self.imagimage.putchunk(pixfft.imag, [0, 0, ichan]) del pixval, pixfft self.realimage.close() self.imagimage.close() # weighted mean if len(imshape) == 4: npol = imshape[3] for ichan in range(nchan): for ipol in range(npol): pixout = numpy.zeros(shape=(nx, ny), dtype=complex) denom = numpy.zeros(shape=(nx, ny), dtype=float) for i in range(nfile): self.realimage = ia.newimage(self.tmprealname[i]) self.imagimage = ia.newimage(self.tmpimagname[i]) pixval = self.realimage.getchunk([0, 0, ichan, ipol], [ nx - 1, ny - 1, ichan, ipol ]) + self.imagimage.getchunk( [0, 0, ichan, ipol], [nx - 1, ny - 1, ichan, ipol]) * 1.0j pixval = pixval.reshape((nx, ny)) pixout = pixout + pixval * weights[i] denom = denom + weights[i] self.realimage.close() self.imagimage.close() pixout = pixout / denom pixout = pixout.reshape((nx, ny, 1, 1)) self.realimage = ia.newimage(self.tmprealname[0]) self.imagimage = ia.newimage(self.tmpimagname[0]) self.realimage.putchunk(pixout.real, [0, 0, ichan, ipol]) self.imagimage.putchunk(pixout.imag, [0, 0, ichan, ipol]) self.realimage.close() self.imagimage.close() elif len(imshape) == 3: for ichan in range(nchan): pixout = numpy.zeros(shape=(nx, ny), dtype=complex) denom = numpy.zeros(shape=(nx, ny), dtype=float) for i in range(nfile): self.realimage = ia.newimage(self.tmprealname[i]) self.imagimage = ia.newimage(self.tmpimagname[i]) pixval = self.realimage.getchunk([0, 0, ichan], [nx - 1, ny - 1, ichan]) pixval = pixval.reshape((nx, ny)) pixout = pixout + pixval * weights[i] denom = denom + weights[i] self.realimage.close() self.imagimage.close() pixout = pixout / denom pixout = pixout.reshape((nx, ny, 1)) self.realimage = ia.newimage(self.tmprealname[0]) self.imagimage = ia.newimage(self.tmpimagname[0]) self.realimage.putchunk(pixout.real, [0, 0, ichan]) self.imagimage.putchunk(pixout.imag, [0, 0, ichan]) self.realimage.close() self.imagimage.close() # inverse FFT self.realimage = ia.newimage(self.tmprealname[0]) self.imagimage = ia.newimage(self.tmpimagname[0]) if len(imshape) == 4: npol = imshape[3] for ichan in range(nchan): for ipol in range(npol): pixval = self.realimage.getchunk([0, 0, ichan, ipol], [ nx - 1, ny - 1, ichan, ipol ]) + self.imagimage.getchunk( [0, 0, ichan, ipol], [nx - 1, ny - 1, ichan, ipol]) * 1.0j pixval = pixval.reshape((nx, ny)) pixifft = npfft.ifft2(pixval) pixifft = pixifft.reshape((nx, ny, 1, 1)) outimage.putchunk(pixifft.real, [0, 0, ichan, ipol]) del pixval, pixifft elif len(imshape) == 3: for ichan in range(nchan): pixval = self.realimage.getchunk( [0, 0, ichan], [nx - 1, ny - 1, ichan]) + self.imagimage.getchunk( [0, 0, ichan], [nx - 1, ny - 1, ichan]) * 1.0j pixval = pixval.reshape((nx, ny)) pixifft = npfft.ifft2(pixval) pixifft = pixifft.reshape((nx, ny, 1)) outimage.putchunk(pixifft.real, [0, 0, ichan]) del pixval, pixifft if maskedvalue is not None: outimage.putchunk(outimage.getchunk() + maskedvalue) # handling of output image mask maskstr = "" for name in self.infiles: if len(maskstr) > 0: maskstr += " || " maskstr += ("mask('%s')" % (name)) outimage.calcmask(maskstr, name="basketweaving", asdefault=True) self.realimage.close() self.imagimage.close() outimage.close()
image2[0][0] * (1 - sliderRatios[0])) phase_mix = np.zeros(image2[0][0].shape) # case 3 if case == Cases.UniMagandPhase: mag_mix = np.ones(image2[0][0].shape) # ones array phase_mix = np.add((image2[0][1] * sliderRatios[1]), (image1[0][1] * (1 - sliderRatios[1]))) # case 4 if case == Cases.UniMagandUniPhase: mag_mix = np.ones(image2[0][0].shape) # ones array phase_mix = np.zeros(image2[0][0].shape) # case 5 if case == Cases.RealandImag: real_mix = np.add(image1[0][2] * sliderRatios[0], image2[0][2] * (1 - sliderRatios[0])) imag_mix = np.add(image2[0][3] * (sliderRatios[1]), image1[0][3] * (1 - sliderRatios[1])) if case == Cases.RealandImag: imag_mix = (1j * imag_mix) new_array = np.add(real_mix, imag_mix) else: phase_mix = np.exp(1j * phase_mix) new_array = np.multiply(phase_mix, mag_mix) output = np.real(ifft2(new_array)) return output # -> ndarray
def tiePavlov(Is, Ir, energy, z1, z2, pix_size, delta, beta, bg_val, scale): """ Phase retrieval using the Transport of Intensity Equation for homogeneous samples in the case of speckles Parameters ---------- arg1 : Is Image with the sample and the membrane arg2 : Ir Image with the membrane only arg3 : str energy = mean x-ray energy (keV) arg4: float z1 = source to sample distance (m) arg5: float z2 = sample to detector distance (m) arg6: float pix_size = size of the image pixels (m) arg7: float delta = refractive index arg8: float beta = absorption par t of the refactive index arg9: float bg_val = background intensity in img_in (e.g. 0, 1, 100...) arg10: float scale = parameter in the low-frequency filter (e.g., 2) (added by KMP) Returns ------- float img_thickness = image of sample thickness (m) """ lambda_energy = kevToLambda(energy) waveNumber = (2 * pi) / lambda_energy mu = 2 * waveNumber * beta magnificationFactor = (z1 + z2) / z1 pix_size = pix_size * magnificationFactor #pix_size = pix_size * magnificationFactor sigmaSource = 150.e-6 gamma = delta / beta is_divided_by_Ir = np.true_divide(Is, Ir) numerator = 1 - is_divided_by_Ir # average_image = np.mean(numerator) # Correction on the average image. Now the average of the new array is ~0 # numerator = numerator - average_image saveEdf(numerator, 'ImageNew.edf') padCol = 1600 padRow = 1600 width, height = numerator.shape numerator = np.pad(numerator, ((padRow, padRow), (padCol, padCol)), 'reflect') fftNumerator = fftshift(fft2(numerator)) Nx, Ny = fftNumerator.shape print('Nx:' + str(Nx) + ' Ny:' + str(Ny)) u, v = np.meshgrid(np.arange(0, Nx), np.arange(0, Ny)) u = (u - (Nx / 2)) v = (v - (Ny / 2)) u_m = u / (Nx * pix_size) v_m = v / (Ny * pix_size) uv_sqr = np.transpose(u_m**2 + v_m**2) # ie (u2+v2) # without taking care of source size # denominator = 1 + pi * gamma * z2 * lambda_energy * k_sqr # Beltran et al method to deblur with source denominator = 1 + pi * (gamma * z2 - waveNumber * sigmaSource * sigmaSource) * lambda_energy * uv_sqr # denominator *= magnificationFactor tmp = fftNumerator / denominator # Low pass filter sigma_x = ((1 / (Nx * pix_size * 1.6)) * scale)**2 sigma_y = ((1 / (Ny * pix_size * 1.6)) * scale)**2 f = (1. - np.exp(-(u_m**2 / (2. * sigma_x) + v_m**2 / (2. * sigma_y))) ) # ie f(x,y) lff = np.transpose(f) # ie LFF # Application of the Low pass filter tmp = lff * tmp # inverse fourier transform tmpThickness = ifft2(ifftshift(tmp)) # F-1 img_thickness = np.real(tmpThickness) # Division by mu img_thickness = img_thickness / mu # multiplication to be in micron img_thickness = img_thickness * 1e6 # unpadding img_thickness = img_thickness[padRow:padRow + width, padCol:padCol + height] img_thickness += bg_val return img_thickness