def register(image1, image2): trim = 8 image1 = image1[trim:-trim, trim:-trim] image2 = image2[trim:-trim, trim:-trim] fft1 = scipy.fftpack.fft2(image1) fft2 = scipy.fftpack.fft2(image2) fft1 = scipy.fftpack.fftshift(fft1, axes=[0]) fft2 = scipy.fftpack.fftshift(fft2, axes=[0]) c = int(fft1.shape[0] / 2.0) fft1 = fft1[:,:c+1] fft2 = fft2[:,:c+1] mag1 = numpy.abs(fft1) mag2 = numpy.abs(fft2) mrc.write(mag1, 'mag1.mrc') mrc.write(mag2, 'mag2.mrc') center = c,0 output_shape = c,c print 'P1' p1 = polar_transform(mag1, output_shape, center) #scipy.misc.imsave('p1.jpg', p1) mrc.write(p1, 'p1.mrc') print 'P2' p2 = polar_transform(mag2, output_shape, center) #scipy.misc.imsave('p2.jpg', p2) mrc.write(p2, 'p2.mrc') pc = correlator.phase_correlate(p1, p2, zero=False) #pc = correlator.cross_correlate(p1, p2) mrc.write(pc, 'pc.mrc')
def correlate_template(self): ''' Correlate template that is already created and configured. ''' fromimage = 'original' if self.__results[fromimage] is None or self.__results['template'] is None: raise RuntimeError('need image %s and template before correlation' % (fromimage,)) edges = self.__results[fromimage] edges = self.maskBlack(edges) template = self.__results['template'] cortype = self.correlation_config['cortype'] corfilt = self.correlation_config['corfilt'] if cortype == 'cross': cc = correlator.cross_correlate(edges, template) elif cortype == 'phase': cc = correlator.phase_correlate(edges, template, zero=False) else: raise RuntimeError('bad correlation type: %s' % (cortype,)) if corfilt is not None: kernel = convolver.gaussian_kernel(*corfilt) self.convolver.setKernel(kernel) cc = self.convolver.convolve(image=cc) self.__update_result('correlation', cc) if self.save_mrc: mrc.write(cc, 'correlation.mrc')
def correlate_template(self): fromimage = 'edges' if None in (self.__results[fromimage], self.__results['template']): raise RuntimeError('need image %s and template before correlation' % (fromimage,)) edges = self.__results[fromimage] template = self.__results['template'] cortype = self.correlation_config['cortype'] corfilt = self.correlation_config['corfilt'] if cortype == 'cross': cc = correlator.cross_correlate(edges, template) elif cortype == 'phase': cc = correlator.phase_correlate(edges, template, zero=False) else: raise RuntimeError('bad correlation type: %s' % (cortype,)) cc = numpy.absolute(cc) if corfilt is not None: kernel = convolver.gaussian_kernel(*corfilt) self.edgefinder.setKernel(kernel) cc = self.edgefinder.convolve(image=cc) #cc = imagefun.zscore(smooth) #cc = imagefun.zscore(cc) self.__update_result('correlation', cc) if self.save_mrc: mrc.write(cc, 'correlation.mrc')
def getShift(imgdata1, imgdata2): # assumes images are square print "Finding shift between", apDisplay.short(imgdata1["filename"]), "and", apDisplay.short(imgdata2["filename"]) dimension1 = imgdata1["camera"]["dimension"]["x"] binning1 = imgdata1["camera"]["binning"]["x"] dimension2 = imgdata2["camera"]["dimension"]["x"] binning2 = imgdata2["camera"]["binning"]["x"] finalsize = 512 # test to make sure images are at same mag if imgdata1["scope"]["magnification"] != imgdata2["scope"]["magnification"]: apDisplay.printWarning("Defocus pairs are at different magnifications, so shift can't be calculated.") return None # test to see if images capture the same area if (dimension1 * binning1) != (dimension2 * binning2): apDisplay.printWarning("Defocus pairs do not capture the same imaging area, so shift can't be calculated.") return None # images must not be less than finalsize (currently 512) pixels. This is arbitrary but for good reason if dimension1 < finalsize or dimension2 < finalsize: apDisplay.printWarning("Images must be greater than " + finalsize + " pixels to calculate shift.") return None # low pass filter 2 images to twice the final pixelsize BEFORE binning shrinkfactor1 = dimension1 / finalsize shrinkfactor2 = dimension2 / finalsize binned1 = apImage.filterImg(imgdata1["image"], 1.0, shrinkfactor1 * 2) binned2 = apImage.filterImg(imgdata2["image"], 1.0, shrinkfactor2 * 2) # now bin 2 images binned1 = apImage.binImg(binned1, shrinkfactor1) binned2 = apImage.binImg(binned2, shrinkfactor2) ### fix for non-square images, correlation fails on non-square images mindim = min(binned1.shape) binned1 = binned1[:mindim, :mindim] binned2 = binned2[:mindim, :mindim] ### use phase correlation, performs better than cross pc = correlator.phase_correlate(binned1, binned2) apImage.arrayToMrc(pc, "phaseCorrelate.mrc") ### find peak, filtering to 10.0 helps peak = peakfinder.findSubpixelPeak(pc, lpf=10.0) subpixpeak = peak["subpixel peak"] shift = correlator.wrap_coord(subpixpeak, pc.shape) peak["scalefactor"] = dimension2 / float(dimension1) # print shift[0]*shrinkfactor1, shift[1]*shrinkfactor1 xshift = int(round(shift[0] * shrinkfactor1)) yshift = int(round(shift[1] * shrinkfactor1)) peak["shift"] = numpy.array((xshift, yshift)) apDisplay.printMsg("Determined shifts: %f %f" % (peak["shift"][0], peak["shift"][1])) # print peak['shift'] # sys.exit(1) return peak
def register2(image1, image2, angles): im2filt = scipy.ndimage.spline_filter(image2) peaks = [] for angle in angles: image2 = scipy.ndimage.rotate(im2filt, angle, reshape=False) #mrc.write(image2, 'rot.mrc') pc = correlator.phase_correlate(image1, image2, zero=False) mrc.write(pc, 'pc.mrc') peak = peakfinder.findSubpixelPeak(pc) result = (angle, peak['pixel peak value'], peak['subpixel peak value'], peak['snr']) print result peaks.append(result) return peaks
def correlateOriginal(self, index, imagedata): if index == 0: self.originalimage = imagedata['image'] unbinned = {'row': 0.0, 'col': 0.0} else: ## correlate self.startTimer('scope change correlation') try: correlation_type = self.settings['correlation type'] except KeyError: correlation_type = 'phase' if correlation_type == 'cross': cor = correlator.cross_correlate(self.originalimage, imagedata['image']) elif correlation_type == 'phase': cor = correlator.phase_correlate(self.originalimage, imagedata['image'], False, wiener=True) else: raise RuntimeError('invalid correlation type') self.stopTimer('scope change correlation') self.displayCorrelation(cor) ## find peak self.startTimer('shift peak') peak = peakfinder.findSubpixelPeak(cor) self.stopTimer('shift peak') self.logger.debug('Peak %s' % (peak, )) pixelpeak = peak['subpixel peak'] self.startTimer('shift display') self.displayPeak(pixelpeak) self.stopTimer('shift display') peakvalue = peak['subpixel peak value'] shift = correlator.wrap_coord(peak['subpixel peak'], cor.shape) self.logger.debug('pixel shift (row,col): %s' % (shift, )) ## need unbinned result binx = imagedata['camera']['binning']['x'] biny = imagedata['camera']['binning']['y'] unbinned = {'row': shift[0] * biny, 'col': shift[1] * binx} shiftinfo = { 'previous': self.originalimage, 'next': imagedata, 'pixel shift': unbinned } return shiftinfo
def checkMoveError(self): #maxerror = self.settings['max error'] #limit = (int(maxerror*2), int(maxerror*2)) oldshape = self.oldimagedata['image'].shape limit = oldshape location = oldshape[0] / 2.0 - 0.5 + self.origmove[ 0], oldshape[1] / 2.0 - 0.5 + self.origmove[1] im1 = imagefun.crop_at(self.origimagedata['image'], location, limit, mode='constant', cval=0.0) im2 = imagefun.crop_at(self.newimagedata['image'], 'center', limit) pc = correlator.phase_correlate(im2, im1, zero=False) pc = scipy.ndimage.gaussian_filter(pc, 1) subpixelpeak = self.peakfinder.subpixelPeak(newimage=pc, guess=(0.5, 0.5), limit=limit) res = self.peakfinder.getResults() unsignedpixelpeak = res['unsigned pixel peak'] peaktargets = [(unsignedpixelpeak[1], unsignedpixelpeak[0])] r_error = subpixelpeak[0] c_error = subpixelpeak[1] self.setImage(pc, 'Correlation') peaktargets = [(unsignedpixelpeak[1], unsignedpixelpeak[0])] self.setTargets(peaktargets, 'Peak') ## calculate error distance scope = self.newimagedata['scope'] camera = self.newimagedata['camera'] mag = scope['magnification'] tem = scope['tem'] ccdcamera = camera['ccdcamera'] pixelsize = self.pcal.retrievePixelSize(tem, ccdcamera, mag) cbin = camera['binning']['x'] rbin = camera['binning']['y'] rpix = r_error * rbin cpix = c_error * cbin pixdist = math.hypot(rpix, cpix) distance = pixdist * pixelsize return r_error, c_error, distance
def correlateOriginal(self,index,imagedata): if index == 0: self.originalimage = imagedata['image'] unbinned = {'row':0.0, 'col': 0.0} else: ## correlate self.startTimer('scope change correlation') try: correlation_type = self.settings['correlation type'] except KeyError: correlation_type = 'phase' if correlation_type == 'cross': cor = correlator.cross_correlate(self.originalimage,imagedata['image']) elif correlation_type == 'phase': cor = correlator.phase_correlate(self.originalimage,imagedata['image'],False,wiener=True) else: raise RuntimeError('invalid correlation type') self.stopTimer('scope change correlation') self.displayCorrelation(cor) ## find peak self.startTimer('shift peak') peak = peakfinder.findSubpixelPeak(cor) self.stopTimer('shift peak') self.logger.debug('Peak %s' % (peak,)) pixelpeak = peak['subpixel peak'] self.startTimer('shift display') self.displayPeak(pixelpeak) self.stopTimer('shift display') peakvalue = peak['subpixel peak value'] shift = correlator.wrap_coord(peak['subpixel peak'], cor.shape) self.logger.debug('pixel shift (row,col): %s' % (shift,)) ## need unbinned result binx = imagedata['camera']['binning']['x'] biny = imagedata['camera']['binning']['y'] unbinned = {'row':shift[0] * biny, 'col': shift[1] * binx} shiftinfo = {'previous': self.originalimage, 'next': imagedata, 'pixel shift': unbinned} return shiftinfo
def checkMoveError(self): #maxerror = self.settings['max error'] #limit = (int(maxerror*2), int(maxerror*2)) oldshape = self.oldimagedata['image'].shape limit = oldshape location = oldshape[0]/2.0-0.5+self.origmove[0], oldshape[1]/2.0-0.5+self.origmove[1] im1 = imagefun.crop_at(self.origimagedata['image'], location, limit, mode='constant', cval=0.0) im2 = imagefun.crop_at(self.newimagedata['image'], 'center', limit) pc = correlator.phase_correlate(im2, im1, zero=False) pc = scipy.ndimage.gaussian_filter(pc,1) subpixelpeak = self.peakfinder.subpixelPeak(newimage=pc, guess=(0.5,0.5), limit=limit) res = self.peakfinder.getResults() unsignedpixelpeak = res['unsigned pixel peak'] peaktargets = [(unsignedpixelpeak[1], unsignedpixelpeak[0])] r_error = subpixelpeak[0] c_error = subpixelpeak[1] self.setImage(pc, 'Correlation') peaktargets = [(unsignedpixelpeak[1], unsignedpixelpeak[0])] self.setTargets(peaktargets, 'Peak') ## calculate error distance scope = self.newimagedata['scope'] camera = self.newimagedata['camera'] mag = scope['magnification'] tem = scope['tem'] ccdcamera = camera['ccdcamera'] pixelsize = self.pcal.retrievePixelSize(tem, ccdcamera, mag) cbin = camera['binning']['x'] rbin = camera['binning']['y'] rpix = r_error * rbin cpix = c_error * cbin pixdist = math.hypot(rpix,cpix) distance = pixdist * pixelsize return r_error, c_error, distance
def removeStageAlphaBacklash(self, tilts, preset_name, target, emtarget): if len(tilts) < 2: raise ValueError ## change to parent preset try: parentname = target['image']['preset']['name'] except: adjust = False else: adjust = True ## acquire parent preset image, initial image if adjust: isoffset = self.getImageShiftOffset() self.presetsclient.toScope(parentname) self.setImageShiftOffset(isoffset) imagedata0 = self.acquireCorrectedCameraImageData(0) ## tilt then return in slow increments delta = math.radians(5.0) n = 5 increment = delta / n if tilts[1] - tilts[0] > 0: sign = -1 else: sign = 1 alpha = tilts[0] + sign * delta self.instrument.tem.StagePosition = {'a': alpha} time.sleep(1.0) for i in range(n): alpha -= sign * increment self.instrument.tem.StagePosition = {'a': alpha} time.sleep(1.0) if adjust: ## acquire parent preset image, final image imagedata1 = self.acquireCorrectedCameraImageData(1) self.presetsclient.toScope(preset_name) ## return to tomography preset if emtarget['movetype'] == 'image shift': presetdata = self.presetsclient.getPresetFromDB(preset_name) self.moveAndPreset(presetdata, emtarget) else: self.presetsclient.toScope(preset_name) self.setImageShiftOffset(isoffset) ## find shift between image0, image1 pc = correlator.phase_correlate(imagedata0['image'], imagedata1['image'], False) peakinfo = peakfinder.findSubpixelPeak(pc, lpf=1.5) subpixelpeak = peakinfo['subpixel peak'] shift = correlator.wrap_coord(subpixelpeak, imagedata0['image'].shape) shift = {'row': shift[0], 'col': shift[1]} ## transform pixel to image shift oldscope = imagedata0['scope'] newscope = self.calclients['image shift'].transform( shift, oldscope, imagedata0['camera']) ishiftx = newscope['image shift']['x'] - oldscope['image shift'][ 'x'] ishifty = newscope['image shift']['y'] - oldscope['image shift'][ 'y'] oldishift = self.instrument.tem.ImageShift newishift = { 'x': oldishift['x'] + ishiftx, 'y': oldishift['y'] + ishifty } self.logger.info( 'adjusting imageshift after backlash: dx,dy = %s,%s' % (ishiftx, ishifty)) self.instrument.tem.ImageShift = newishift
def removeStageAlphaBacklash(self, tilts, preset_name, target, emtarget): if len(tilts) < 2: raise ValueError ## change to parent preset try: parentname = target['image']['preset']['name'] except: adjust = False else: adjust = True ## acquire parent preset image, initial image if adjust: isoffset = self.getImageShiftOffset() self.presetsclient.toScope(parentname) self.setImageShiftOffset(isoffset) imagedata0 = self.acquireCorrectedCameraImageData(0) ## tilt then return in slow increments delta = math.radians(5.0) n = 5 increment = delta/n if tilts[1] - tilts[0] > 0: sign = -1 else: sign = 1 alpha = tilts[0] + sign*delta self.instrument.tem.StagePosition = {'a': alpha} time.sleep(1.0) for i in range(n): alpha -= sign*increment self.instrument.tem.StagePosition = {'a': alpha} time.sleep(1.0) if adjust: ## acquire parent preset image, final image imagedata1 = self.acquireCorrectedCameraImageData(1) self.presetsclient.toScope(preset_name) ## return to tomography preset if emtarget['movetype'] == 'image shift': presetdata = self.presetsclient.getPresetFromDB(preset_name) self.moveAndPreset(presetdata, emtarget) else: self.presetsclient.toScope(preset_name) self.setImageShiftOffset(isoffset) ## find shift between image0, image1 pc = correlator.phase_correlate(imagedata0['image'], imagedata1['image'], False) peakinfo = peakfinder.findSubpixelPeak(pc, lpf=1.5) subpixelpeak = peakinfo['subpixel peak'] shift = correlator.wrap_coord(subpixelpeak, imagedata0['image'].shape) shift = {'row': shift[0], 'col': shift[1]} ## transform pixel to image shift oldscope = imagedata0['scope'] newscope = self.calclients['image shift'].transform(shift, oldscope, imagedata0['camera']) ishiftx = newscope['image shift']['x'] - oldscope['image shift']['x'] ishifty = newscope['image shift']['y'] - oldscope['image shift']['y'] oldishift = self.instrument.tem.ImageShift newishift = {'x': oldishift['x'] + ishiftx, 'y': oldishift['y'] + ishifty} self.logger.info('adjusting imageshift after backlash: dx,dy = %s,%s' % (ishiftx,ishifty)) self.instrument.tem.ImageShift = newishift
def getShift(imgdata1, imgdata2): #assumes images are square print "Finding shift between", apDisplay.short( imgdata1['filename']), "and", apDisplay.short(imgdata2['filename']) dimension1 = imgdata1['camera']['dimension']['x'] binning1 = imgdata1['camera']['binning']['x'] dimension2 = imgdata2['camera']['dimension']['x'] binning2 = imgdata2['camera']['binning']['x'] finalsize = 512 #test to make sure images are at same mag if imgdata1['scope']['magnification'] != imgdata2['scope']['magnification']: apDisplay.printWarning( "Defocus pairs are at different magnifications, so shift can't be calculated." ) return None #test to see if images capture the same area if (dimension1 * binning1) != (dimension2 * binning2): apDisplay.printWarning( "Defocus pairs do not capture the same imaging area, so shift can't be calculated." ) return None #images must not be less than finalsize (currently 512) pixels. This is arbitrary but for good reason if dimension1 < finalsize or dimension2 < finalsize: apDisplay.printWarning("Images must be greater than " + finalsize + " pixels to calculate shift.") return None #low pass filter 2 images to twice the final pixelsize BEFORE binning shrinkfactor1 = dimension1 / finalsize shrinkfactor2 = dimension2 / finalsize binned1 = apImage.filterImg(imgdata1['image'], 1.0, shrinkfactor1 * 2) binned2 = apImage.filterImg(imgdata2['image'], 1.0, shrinkfactor2 * 2) #now bin 2 images binned1 = apImage.binImg(binned1, shrinkfactor1) binned2 = apImage.binImg(binned2, shrinkfactor2) ### fix for non-square images, correlation fails on non-square images mindim = min(binned1.shape) binned1 = binned1[:mindim, :mindim] binned2 = binned2[:mindim, :mindim] ### use phase correlation, performs better than cross pc = correlator.phase_correlate(binned1, binned2) apImage.arrayToMrc(pc, "phaseCorrelate.mrc") ### find peak, filtering to 10.0 helps peak = peakfinder.findSubpixelPeak(pc, lpf=10.0) subpixpeak = peak['subpixel peak'] shift = correlator.wrap_coord(subpixpeak, pc.shape) peak['scalefactor'] = dimension2 / float(dimension1) #print shift[0]*shrinkfactor1, shift[1]*shrinkfactor1 xshift = int(round(shift[0] * shrinkfactor1)) yshift = int(round(shift[1] * shrinkfactor1)) peak['shift'] = numpy.array((xshift, yshift)) apDisplay.printMsg("Determined shifts: %f %f" % (peak['shift'][0], peak['shift'][1])) #print peak['shift'] #sys.exit(1) return peak