def correltrack(data, start=0, avgover=10, pixelsize=70.0, centersize=7, centroidfrac=1.5): cs = centersize shp = [d for d in data.shape if d > 1] nsteps = long((shp[2] - start) / avgover) shh = (shp[0] / 2, shp[1] / 2) xctw = np.zeros((2 * centersize + 1, 2 * centersize + 1, nsteps)) shifts = [] i1 = data[:, :, start:start + avgover].squeeze().mean(axis=2) I1 = fftn(i1) for i in range(nsteps): xc = abs( ifftshift( ifftn(I1 * ifftn(data[:, :, start + i * avgover:start + (i + 1) * avgover].squeeze().mean(axis=2))))) xct = xc - xc.min() xct = (xct - xct.max() / centroidfrac) * (xct > xct.max() / centroidfrac) xctw[:, :, i] = xct[shh[0] - cs:shh[0] + cs + 1, shh[1] - cs:shh[1] + cs + 1] shifts.append(scipy.ndimage.measurements.center_of_mass(xctw[:, :, i])) sh = np.array(shifts) t = start + np.arange(nsteps) * avgover sh = pixelsize * (sh - sh[0]) return t, sh, xctw
def correlateFrames(A, B): A = A.squeeze()/A.mean() - 1 B = B.squeeze()/B.mean() - 1 X, Y = np.mgrid[0.0:A.shape[0], 0.0:A.shape[1]] C = ifftshift(np.abs(ifftn(fftn(A)*ifftn(B)))) Cm = C.max() Cp = np.maximum(C - 0.5*Cm, 0) Cpsum = Cp.sum() x0 = (X*Cp).sum()/Cpsum y0 = (Y*Cp).sum()/Cpsum return x0 - A.shape[0]/2, y0 - A.shape[1]/2, Cm, Cpsum
def correlateFrames(A, B): A = A.squeeze() / A.mean() - 1 B = B.squeeze() / B.mean() - 1 X, Y = np.mgrid[0.0:A.shape[0], 0.0:A.shape[1]] C = ifftshift(np.abs(ifftn(fftn(A) * ifftn(B)))) Cm = C.max() Cp = np.maximum(C - 0.5 * Cm, 0) Cpsum = Cp.sum() x0 = (X * Cp).sum() / Cpsum y0 = (Y * Cp).sum() / Cpsum return x0 - A.shape[0] / 2, y0 - A.shape[1] / 2, Cm, Cpsum
def calcCorrShift(im1, im2): im1 = im1 - im1.mean() im2 = im2 - im2.mean() xc = np.abs(ifftshift(ifftn(fftn(im1) * ifftn(im2)))) xct = (xc - xc.max() / 1.1) * (xc > xc.max() / 1.1) print((xct.shape)) #figure(1) #imshow(xct) #dx, dy = ndimage.measurements.center_of_mass(xct) #print np.where(xct==xct.max()) dx, dy = np.where(xct == xct.max()) return dx[0] - im1.shape[0] / 2, dy[0] - im1.shape[1] / 2
def setIllumPattern(pattern, z0): global illPattern, illZOffset, illPCache sx, sy = pattern.shape psx, psy, sz = interpModel.shape il = np.zeros([sx,sy,sz], 'f') il[:,:,sz/2] = pattern ps = np.zeros_like(il) if sx > psx: ps[(sx/2-psx/2):(sx/2+psx/2), (sy/2-psy/2):(sy/2+psy/2), :] = interpModel else: ps[:,:,:] = interpModel[(psx/2-sx/2):(psx/2+sx/2), (psy/2-sy/2):(psy/2+sy/2), :] ps= ps/ps[:,:,sz/2].sum() illPattern = abs(ifftshift(ifftn(fftn(il)*fftn(ps)))).astype('f') illPCache = None
def propagate(self, F, z): """ Propagate a complex pupil, F, a distance z from the nominal focus and return the electric field amplitude Parameters ========== F : 2D array complex pupil z : float distance in nm to propagate """ pf = self.propFac*float(z) fs = F*self.pfm*(np.cos(pf) + j*np.sin(pf)) self._F[:] = ifftshift(fs) self._plan_F_f() return fftshift(self._f/np.sqrt(self._f.size))
def propagate_r(self, f, z): """ Backpropagate an electric field distribution, f, at defocus z to the nominal focus and return the complex pupil Parameters ---------- f : 2D array complex electric field amplitude z : float nominal distance of plane from focus in nm Returns ------- """ self._f[:] = fftshift(f) self._plan_f_F() pf = -self.propFac*float(z) return (ifftshift(self._F)*(np.cos(pf)+j*np.sin(pf)))/np.sqrt(self._f.size)
def correltrack2(data, start=0, avgover=10, pixelsize=70.0, centersize=15, centroidfac=0.6, roi=[0, None, 0, None]): cs = centersize shp = [d for d in data.shape if d > 1] nsteps = long((shp[2] - start) / avgover) xctw = np.zeros((2 * centersize + 1, 2 * centersize + 1, nsteps)) shifts = [] if avgover > 1: ref = data[:, :, start:start + avgover].squeeze().mean(axis=2) else: ref = data[:, :, start].squeeze() ref = ref[roi[0]:roi[3], roi[1]:roi[3]] refn = ref / ref.mean() - 1 Frefn = fftn(refn) shh = (ref.shape[0] / 2, ref.shape[1] / 2) for i in range(nsteps): comp = data[:, :, start + i * avgover:start + (i + 1) * avgover].squeeze() if len(comp.shape) > 2: comp = comp.mean(axis=2) comp = comp[roi[0]:roi[3], roi[1]:roi[3]] compn = comp / comp.mean() - 1 xc = ifftshift(np.abs(ifftn(Frefn * ifftn(compn)))) xcm = xc.max() xcp = np.maximum(xc - centroidfac * xcm, 0) xctw[:, :, i] = xcp[shh[0] - cs:shh[0] + cs + 1, shh[1] - cs:shh[1] + cs + 1] shifts.append(scipy.ndimage.measurements.center_of_mass(xctw[:, :, i])) sh = np.array(shifts) t = start + np.arange(nsteps) * avgover sh = pixelsize * (sh - sh[0]) return t, sh, xctw
def compare(self): d = 1.0 * self.scope.pa.dsa.squeeze() dm = d / d.mean() - 1 #find x-y drift C = ifftshift(np.abs(ifftn(fftn(dm) * self.FA))) Cm = C.max() Cp = np.maximum(C - 0.5 * Cm, 0) Cpsum = Cp.sum() dx = (self.X * Cp).sum() / Cpsum dy = (self.Y * Cp).sum() / Cpsum ds = ndimage.shift(dm, [-dx, -dy]) * self.mask #print A.shape, As.shape ds_A = (ds - self.refA) return dx, dy, self.deltaZ * np.dot(ds_A.ravel(), self.dz) * self.dzn
def compare(self): d = 1.0*self.scope.pa.dsa.squeeze() dm = d/d.mean() - 1 #find x-y drift C = ifftshift(np.abs(ifftn(fftn(dm)*self.FA))) Cm = C.max() Cp = np.maximum(C - 0.5*Cm, 0) Cpsum = Cp.sum() dx = (self.X*Cp).sum()/Cpsum dy = (self.Y*Cp).sum()/Cpsum ds = ndimage.shift(dm, [-dx, -dy])*self.mask #print A.shape, As.shape ds_A = (ds - self.refA) return dx, dy, self.deltaZ*np.dot(ds_A.ravel(), self.dz)*self.dzn
def correlateAndCompareFrames(A, B): A = A.squeeze() / A.mean() - 1 B = B.squeeze() / B.mean() - 1 X, Y = np.mgrid[0.0:A.shape[0], 0.0:A.shape[1]] C = ifftshift(np.abs(ifftn(fftn(A) * ifftn(B)))) Cm = C.max() Cp = np.maximum(C - 0.5 * Cm, 0) Cpsum = Cp.sum() x0 = (X * Cp).sum() / Cpsum y0 = (Y * Cp).sum() / Cpsum dx, dy = x0 - A.shape[0] / 2, y0 - A.shape[1] / 2 As = ndimage.shift(A, [-dx, -dy]) #print A.shape, As.shape return (As - B).mean(), dx, dy
def correlateAndCompareFrames(A, B): A = A.squeeze()/A.mean() - 1 B = B.squeeze()/B.mean() - 1 X, Y = np.mgrid[0.0:A.shape[0], 0.0:A.shape[1]] C = ifftshift(np.abs(ifftn(fftn(A)*ifftn(B)))) Cm = C.max() Cp = np.maximum(C - 0.5*Cm, 0) Cpsum = Cp.sum() x0 = (X*Cp).sum()/Cpsum y0 = (Y*Cp).sum()/Cpsum dx, dy = x0 - A.shape[0]/2, y0 - A.shape[1]/2 As = ndimage.shift(A, [-dx, -dy]) #print A.shape, As.shape return (As -B).mean(), dx, dy
def propagate(self, F, z): """ Propagate a complex pupil, F, a distance z from the nominal focus and return the electric field amplitude Parameters ========== F : 2D array complex pupil z : float distance in nm to propagate """ pf = self.propFac*float(z) r = max(self.appR*(1 -self.apertureZGrad*z), 0) M = (self.x*self.x + self.y*self.y) < (r*r) fs = F*M*self.pfm*(np.cos(pf) + j*np.sin(pf)) self._F[:] = fftshift(fs) self._plan_F_f() return ifftshift(self._f/np.sqrt(self._f.size))
def propagate(self, F, z): return ifftshift(ifftn(F*np.exp(self.propFac*z)))
def correction_light(I, method, show_light, mask=None): """Corrige la derive eclairement :I: array_like ou iplimage :method: 'polynomial' or 'frequency' :show_light: option affiche correction (true|false) :mask: array de zone non interet :returns: iplimage 32bit """ from progress import * import Tkinter if type(I) == cv.iplimage: if I.nChannels == 3: if method == 'None': I = RGB2L(I) I = cv2array(I)[:, :, 0] I = pymorph.hmin(I, 15, pymorph.sedisk(3)) I = array2cv(I) cv.EqualizeHist(I, I) return I I = RGB2L(I) I_32bit = cv.CreateImage(cv.GetSize(I), cv.IPL_DEPTH_32F, 1) cv.ConvertScale(I, I_32bit, 3000.0, 0.0) I = cv.CloneImage(I_32bit) I = cv2array(I)[:, :, 0] elif len(I.shape) == 3: I = (I[:, :, 0] + I[:, :, 0] + I[:, :, 0])\ / 3.0 # A modifier: non utiliser dans notre cas elif method == 'None': I = array2cv(I) cv.EqualizeHist(I, I) return I I = np.log(I + 10 ** (-6)) (H, W) = np.shape(I) I_out = I * 0 + 10 ** (-6) if method == 'polynomial': ## I = M.A avec A coeff. du polynome I_flat = I.flatten() degree = 3 print("modification degree 3") #degree du polynome nb_coeff = (degree + 1) * (degree + 2) / 2 # nombre coefficient [yy, xx] = np.meshgrid(np.arange(W, dtype=np.float64), np.arange(H, dtype=np.float64)) if mask is not None: xx[mask] = 0 yy[mask] = 0 # Creation de M try: M = np.zeros((H * W, nb_coeff), dtype=np.float64) except MemoryError: print MemoryError return MemoryError i, j = 0, 0 # i,j degree de x,y #Bar progression bar = Tkinter.Tk(className='Correcting Light...') m = Meter(bar, relief='ridge', bd=3) m.pack(fill='x') m.set(0.0, 'Starting correction...') for col in np.arange(nb_coeff): M[:, col] = (xx.flatten() ** i) * (yy.flatten() ** j) i += 1 m.set(0.5 * float(col) / (nb_coeff - 1)) if i + j == degree + 1: i = 0 j += 1 # Resolution au sens des moindres carree: pseudo-inverse try: M = pl.pinv(M) A = np.dot(M, I_flat) except ValueError: return ValueError # Calcul de la surface i, j = 0, 0 surface = np.zeros((H, W), dtype=np.float64) for cmpt in np.arange(nb_coeff): surface += A[cmpt] * (xx ** i) * (yy ** j) # forme quadratique i += 1 m.set(0.5 + 0.5 * float(cmpt) / (nb_coeff - 1)) if i + j == degree + 1: i = 0 j += 1 bar.destroy() I_out = np.exp(I / surface) light = surface elif method == 'frequency': Rx, Ry = 2, 2 # zero padding N = [H, W] filtre = np.zeros((N[1], N[0])) centre_x = round(N[0] / 2) centre_y = round(N[1] / 2) print("FFT2D...") I_fourier = pl.fftshift(pl.fft2(I, N)) # Gaussian filter [xx, yy] = np.meshgrid(np.arange(N[0], dtype=np.float), np.arange(N[1], dtype=np.float)) filtre = np.exp(-2 * ((xx - centre_x) ** 2 + (yy - centre_y) ** 2) / (Rx ** 2 + Ry ** 2)) filtre = pl.transpose(filtre) I_fourier = I_fourier * filtre print("IFFT2D...") I_out = (np.abs(pl.ifft2(pl.ifftshift(I_fourier), N)))[0:H, 0:W] light = I_out I_out = np.exp(I / I_out) else: light = I * 0 I_out = I # Display Light if show_light: light = ((light - light.min()) * 3000.0 / light.max()).astype('float32') light = array2cv(light) fig = pl.figure() pl.imshow(light) fig.show() I_out = (I_out - I_out.min()) * 3000.0 / I_out.max() I_out = I_out.astype('uint8') #chapeau haut de forme I_out = pymorph.hmin(I_out, 25, pymorph.sedisk(3)) #Conversion en iplimage et ajustement contraste gr = array2cv(I_out) cv.EqualizeHist(gr, gr) return gr
def compare(self): d = 1.0 * self.scope.frameWrangler.currentFrame.squeeze() dm = d / d.mean() - 1 #where is the piezo suppposed to be #nomPos = self.piezo.GetPos(0) nomPos = self.piezo.GetTargetPos(0) #find closest calibration position posInd = np.argmin(np.abs(nomPos - self.calPositions)) #dz = float('inf') #count = 0 #while np.abs(dz) > 0.5*self.deltaZ and count < 1: # count += 1 #retrieve calibration information at this location calPos = self.calPositions[posInd] FA = self.calFTs[:, :, posInd] refA = self.calImages[:, :, posInd] ddz = self.dz[:, posInd] dzn = self.dzn[posInd] #what is the offset between our target position and the calibration position posDelta = nomPos - calPos print('%s' % [nomPos, posInd, calPos, posDelta]) #find x-y drift C = ifftshift(np.abs(ifftn(fftn(dm) * FA))) Cm = C.max() Cp = np.maximum(C - 0.5 * Cm, 0) Cpsum = Cp.sum() dx = (self.X * Cp).sum() / Cpsum dy = (self.Y * Cp).sum() / Cpsum ds = ndimage.shift(dm, [-dx, -dy]) * self.mask #print A.shape, As.shape self.ds_A = (ds - refA) #calculate z offset between actual position and calibration position dz = self.deltaZ * np.dot(self.ds_A.ravel(), ddz) * dzn #posInd += np.round(dz / self.deltaZ) #posInd = int(np.clip(posInd, 0, self.NCalibStates)) # print count, dz #add the offset back to determine how far we are from the target position dz = dz - posDelta # if 1000*np.abs((dz + posDelta))>200 and self.WantRecord: #dz = np.median(self.buffer) # tif.imsave('C:\\Users\\Lab-test\\Desktop\\peakimage.tif', d) # np.savetxt('C:\\Users\\Lab-test\\Desktop\\parameter.txt', self.buffer[-1]) #np.savetxt('C:\\Users\\Lab-test\\Desktop\\posDelta.txt', posDelta) # self.WantRecord = False #return dx, dy, dz + posDelta, Cm, dz, nomPos, posInd, calPos, posDelta return dx, dy, dz, Cm, dz, nomPos, posInd, calPos, posDelta
def _shift_space( self, R ): R_out = pl.zeros(R.shape) for itime, _ in enumerate(self.t): R_out[:,:,itime].real = pl.ifftshift(R[:,:,itime].real) return R_out