Example #1
0
 def affineToText(self, affineresult):
     return openCVcaller.affineToText(affineresult)
	def affineToText(self, affineresult):
		return openCVcaller.affineToText(affineresult)
        def trackStage(self, image0, tilt0, tilt, tilt0targets):
                #import pprint
                #print "SETTINGS:"
                #pprint.pprint(self.settings)
                self.logger.info('Running trackStage')

                self.logger.info('Returning to state of image0')
                presetname = image0['preset']['name']
                emtarget = image0['emtarget']
                pausetime = self.settings['pause']
                self.presetsclient.toScope(presetname, emtarget)
                ### reset the tilt, just in case user changed it while picking targets
                self.instrument.tem.StagePosition = {'a': tilt0}
                if pausetime > 0.1:
                        self.logger.info('Pausing %.1f seconds' %(pausetime,))
                        time.sleep(pausetime)

                ### calculate tilt steps
                maxstepsize = radians(self.settings['stepsize'])
                tilts = self.calculateTiltSteps(tilt0, tilt, maxstepsize)
                self.logger.info('Tilts: %s' % ([("%.1f"%degrees(t)) for t in tilts],))

                ## filter image
                medfilt = int(self.settings['medfilt'])
                lowfilt = float(self.settings['lowfilt'])
                imageold = image0
                arrayold = numpy.asarray(imageold['image'], dtype=numpy.float32)
                if medfilt > 1:
                        arrayold = ndimage.median_filter(arrayold, size=medfilt)
                if lowfilt > 0:
                        arrayold = ndimage.gaussian_filter(arrayold, lowfilt)
                self.setImage(arrayold, 'Image')
                runningresult = numpy.identity(3, numpy.float32)
                # transformTargets for display purposes only
                self.transformTargets(runningresult, tilt0targets)
                retries = 0

                #for tilt in tilts:
                ### use while loop so we can backtrack
                i = 0
                while i < len(tilts)-1:
                        i+=1
                        tilt = float("%.3f"%tilts[i])
                        self.logger.info('Going to tilt angle: %.2f' % (degrees(tilt),))
                        self.instrument.tem.StagePosition = {'a': tilt}
                        is_small_tilt_diff = self.isSmallTiltDifference(tilts,i,tilt0)
                        if pausetime > 0.1:
                                self.logger.info('Pausing %.1f seconds' %(pausetime,))
                                time.sleep(pausetime)
                        self.logger.info('Acquire intermediate tilted parent image')
                        #print 'acquire intertilt'
                        imagenew = self.acquireCorrectedCameraImageData()
                        arraynew = numpy.asarray(imagenew['image'], dtype=numpy.float32)
                        ## if is_small_tilt_diff:
                        ##      # Don't filter if phase correlation will be used
                        ##      medfilt = 0
                        ##      lowfilt = 0
                        ## if medfilt > 1:
                        ##      arraynew = ndimage.median_filter(arraynew, size=medfilt)
                        ## if lowfilt > 0:
                        ##      arraynew = ndimage.gaussian_filter(arraynew, lowfilt)
                        self.setImage(arraynew, 'Image')

                        if is_small_tilt_diff:
                                self.logger.info('Use phase correlation on small tilt')
                                result = numpy.array(self.shiftmatrix_maker.register(arrayold, arraynew))
                        else:
                                self.logger.info('Peter\'s openCV stuff')
                
                                print 'tilt', tilts[i]*180/3.14159
                                try:
                                        result = openCVcaller.matchImages(arrayold, arraynew)
                                        self.logger.info("result matrix= "+str(numpy.asarray(result*100, dtype=numpy.int8).ravel()))
                                except:
                                        self.logger.error('openCV MatchImages failed')
                                        return None,None
                                ## REWRITE THIS PART LATER?
                                check = openCVcaller.checkOpenCVResult(self, result)
                                if check is False:
                                        self.logger.warning("openCV failed: redoing tilt %.2f"%(tilt,))
                                        ### redo this tilt; becomes an infinite loop if the image goes black
                                        retries += 1
                                        if retries <= 2:
                                                if i == len(tilts)-1:
                                                        ### maybe the tilt angle is too high, reduce max angle by 5 percent
                                                        tilts[len(tilts)-1] *= 0.95
                                                i -= 1
                                        else:
                                                retries = 0
                                                print "Tilt openCV FAILED"
                                                self.logger.error("openCV failed: giving up")
                                                return None, None
                                        continue
                                else:
                                        retries = 0                     

                        self.logger.info("result matrix= "+str(numpy.asarray(result*100, dtype=numpy.int8).ravel()))
                        self.logger.info( "Inter Matrix: "+openCVcaller.affineToText(result) )

                        runningresult = numpy.dot(runningresult, result)
                        # transformTargets for display purposes only
                        self.transformTargets(runningresult, tilt0targets)
                        self.logger.info( "Running Matrix: "+openCVcaller.affineToText(runningresult) )
                        self.logger.info("running result matrix= "+str(numpy.asarray(runningresult*100, dtype=numpy.int8).ravel()))
                        imageold = imagenew
                        arrayold = arraynew

                ### copied from Acquisition.acquire:
                ## store EMData to DB to prevent referencing errors
                self.publish(imageold['scope'], database=True)
                self.publish(imageold['camera'], database=True)

                ## convert CameraImageData to AcquisitionImageData
                dim = image0['camera']['dimension']
                pixels = dim['x'] * dim['y']
                pixeltype = str(image0['image'].dtype)
                imagedata = leginondata.AcquisitionImageData(initializer=imageold, preset=image0['preset'], label=self.name,
                        target=image0['target'], list=None, emtarget=image0['emtarget'], 
                        version=0, tiltnumber=self.tiltnumber, pixels=pixels, pixeltype=pixeltype)
                self.setTargets([], 'Peak')
                self.publishDisplayWait(imagedata)

                self.logger.info( "FINAL Matrix: "+openCVcaller.affineToText(runningresult) )
                #self.logger.info('Final Matrix: %s' % (runningresult,))
                return (runningresult, imagedata)
Example #4
0
    def trackStage(self, image0, tilt0, tilt, tilt0targets):
        #import pprint
        #print "SETTINGS:"
        #pprint.pprint(self.settings)
        self.logger.info('Running trackStage')

        self.logger.info('Returning to state of image0')
        presetname = image0['preset']['name']
        emtarget = image0['emtarget']
        pausetime = self.settings['pause']
        self.presetsclient.toScope(presetname, emtarget)
        ### reset the tilt, just in case user changed it while picking targets
        self.instrument.tem.StagePosition = {'a': tilt0}
        if pausetime > 0.1:
            self.logger.info('Pausing %.1f seconds' % (pausetime, ))
            time.sleep(pausetime)

        ### calculate tilt steps
        maxstepsize = radians(self.settings['stepsize'])
        tilts = self.calculateTiltSteps(tilt0, tilt, maxstepsize)
        self.logger.info('Tilts: %s' % ([("%.1f" % degrees(t))
                                         for t in tilts], ))

        ## filter image
        medfilt = int(self.settings['medfilt'])
        lowfilt = float(self.settings['lowfilt'])
        imageold = image0
        arrayold = numpy.asarray(imageold['image'], dtype=numpy.float32)
        if medfilt > 1:
            arrayold = ndimage.median_filter(arrayold, size=medfilt)
        if lowfilt > 0:
            arrayold = ndimage.gaussian_filter(arrayold, lowfilt)
        self.setImage(arrayold, 'Image')
        runningresult = numpy.identity(3, numpy.float32)
        # transformTargets for display purposes only
        self.transformTargets(runningresult, tilt0targets)
        retries = 0

        #for tilt in tilts:
        ### use while loop so we can backtrack
        i = 0
        while i < len(tilts) - 1:
            i += 1
            tilt = float("%.3f" % tilts[i])
            self.logger.info('Going to tilt angle: %.2f' % (degrees(tilt), ))
            self.instrument.tem.StagePosition = {'a': tilt}
            is_small_tilt_diff = self.isSmallTiltDifference(tilts, i, tilt0)
            if pausetime > 0.1:
                self.logger.info('Pausing %.1f seconds' % (pausetime, ))
                time.sleep(pausetime)
            self.logger.info('Acquire intermediate tilted parent image')
            #print 'acquire intertilt'
            imagenew = self.acquireCorrectedCameraImageData()
            arraynew = numpy.asarray(imagenew['image'], dtype=numpy.float32)
            ## if is_small_tilt_diff:
            ##      # Don't filter if phase correlation will be used
            ##      medfilt = 0
            ##      lowfilt = 0
            ## if medfilt > 1:
            ##      arraynew = ndimage.median_filter(arraynew, size=medfilt)
            ## if lowfilt > 0:
            ##      arraynew = ndimage.gaussian_filter(arraynew, lowfilt)
            self.setImage(arraynew, 'Image')

            if is_small_tilt_diff:
                self.logger.info('Use phase correlation on small tilt')
                result = numpy.array(
                    self.shiftmatrix_maker.register(arrayold, arraynew))
            else:
                self.logger.info('Peter\'s openCV stuff')

                print 'tilt', tilts[i] * 180 / 3.14159
                try:
                    result = openCVcaller.matchImages(arrayold, arraynew)
                    self.logger.info("result matrix= " + str(
                        numpy.asarray(result * 100, dtype=numpy.int8).ravel()))
                except:
                    self.logger.error('openCV MatchImages failed')
                    return None, None
                ## REWRITE THIS PART LATER?
                check = openCVcaller.checkOpenCVResult(self, result)
                if check is False:
                    self.logger.warning("openCV failed: redoing tilt %.2f" %
                                        (tilt, ))
                    ### redo this tilt; becomes an infinite loop if the image goes black
                    retries += 1
                    if retries <= 2:
                        if i == len(tilts) - 1:
                            ### maybe the tilt angle is too high, reduce max angle by 5 percent
                            tilts[len(tilts) - 1] *= 0.95
                        i -= 1
                    else:
                        retries = 0
                        print "Tilt openCV FAILED"
                        self.logger.error("openCV failed: giving up")
                        return None, None
                    continue
                else:
                    retries = 0

            self.logger.info(
                "result matrix= " +
                str(numpy.asarray(result * 100, dtype=numpy.int8).ravel()))
            self.logger.info("Inter Matrix: " +
                             openCVcaller.affineToText(result))

            runningresult = numpy.dot(runningresult, result)
            # transformTargets for display purposes only
            self.transformTargets(runningresult, tilt0targets)
            self.logger.info("Running Matrix: " +
                             openCVcaller.affineToText(runningresult))
            self.logger.info("running result matrix= " + str(
                numpy.asarray(runningresult * 100, dtype=numpy.int8).ravel()))
            imageold = imagenew
            arrayold = arraynew

        ### copied from Acquisition.acquire:
        ## store EMData to DB to prevent referencing errors
        self.publish(imageold['scope'], database=True)
        self.publish(imageold['camera'], database=True)

        ## convert CameraImageData to AcquisitionImageData
        dim = image0['camera']['dimension']
        pixels = dim['x'] * dim['y']
        pixeltype = str(image0['image'].dtype)
        imagedata = leginondata.AcquisitionImageData(
            initializer=imageold,
            preset=image0['preset'],
            label=self.name,
            target=image0['target'],
            list=None,
            emtarget=image0['emtarget'],
            version=0,
            tiltnumber=self.tiltnumber,
            pixels=pixels,
            pixeltype=pixeltype)
        self.setTargets([], 'Peak')
        self.publishDisplayWait(imagedata)

        self.logger.info("FINAL Matrix: " +
                         openCVcaller.affineToText(runningresult))
        #self.logger.info('Final Matrix: %s' % (runningresult,))
        return (runningresult, imagedata)
Example #5
0
    def trackStage(self, image0, tilt0, tilt, tilt0targets):
        self.logger.info('Running trackStage')
        retriesmax = 15
        retries = retriesmax
        blur = 3
        thresh = 0
        self.logger.info('Returning to state of image0')
        presetname = image0['preset']['name']
        emtarget = image0['emtarget']
        pausetime = self.settings['pause']
        self.presetsclient.toScope(presetname, emtarget)
        ### reset the tilt, just in case user changed it while picking targets
        self.instrument.tem.StagePosition = {'a': tilt0}
        if pausetime > 0.1:
            self.logger.info('Pausing %.1f seconds' % (pausetime, ))
            time.sleep(pausetime)

        ### calculate tilt steps
        maxstepsize = radians(self.settings['stepsize'])
        tilts = self.calculateTiltSteps(tilt0, tilt, maxstepsize)
        self.logger.info('Tilts: %s' % ([("%.1f" % degrees(t))
                                         for t in tilts], ))

        imageold = image0
        arrayold = numpy.asarray(imageold['image'], dtype=numpy.float32)
        self.setImage(arrayold, 'Image')
        runningresult = numpy.identity(3, numpy.float32)

        # transformTargets for display purposes only
        self.transformTargets(runningresult, tilt0targets)

        #for tilt in tilts:
        ### use while loop so we can backtrack
        i = 0
        while i < len(tilts) - 1:
            i += 1
            tilt = float("%.3f" % tilts[i])
            self.logger.info('Going to tilt angle: %.2f' % (degrees(tilt), ))
            self.instrument.tem.StagePosition = {'a': tilt}
            is_small_tilt_diff = self.isSmallTiltDifference(tilts, i, tilt0)
            if pausetime > 0.1:
                self.logger.info('Pausing %.1f seconds' % (pausetime, ))
                time.sleep(pausetime)
            self.logger.info('Acquire intermediate tilted parent image')
            imagenew = self.acquireCorrectedCameraImageData()
            arraynew = numpy.asarray(imagenew['image'], dtype=numpy.float32)
            self.setImage(arraynew, 'Image')

            if is_small_tilt_diff:
                self.logger.info('Use phase correlation on small tilt')
                result = numpy.array(
                    self.shiftmatrix_maker.register(arrayold, arraynew))
            else:

                print '============ openCV stuff ============'

                self.logger.info('openCV stuff')
                minsize = self.settings['minsize']
                maxsize = self.settings['maxsize']
                openCVcaller.checkArrayMinMax(self, arrayold, arraynew)
                print 'tilt', tilts[i] * 180 / 3.14159
                result = openCVcaller.MatchImages(arrayold, arraynew, blur,
                                                  thresh)
                self.logger.info(
                    "result matrix= " +
                    str(numpy.asarray(result * 100, dtype=numpy.int8).ravel()))
                print "RESULT", result

                check = openCVcaller.checkOpenCVResult(self, result,
                                                       is_small_tilt_diff)
                if check is False:
                    self.logger.warning("openCV failed: redoing tilt %.2f" %
                                        (tilt, ))
                    if retries:
                        i -= 1
                        retries -= 1
                        if retries <= retriesmax / 2:
                            thresh = 1
                            print "THRESH = 1"
                        print "retries =", retries, "out of", retriesmax
                    else:
                        print "Tilt openCV FAILED"
                        self.logger.error("openCV failed: giving up")
                        self.instrument.tem.StagePosition = {'a': tilt0}
                        return None, None
                    continue
                else:
                    retries = 0
                print '============ openCV stuff done ============'

            self.logger.info(
                "result matrix= " +
                str(numpy.asarray(result * 100, dtype=numpy.int8).ravel()))
            self.logger.info("Inter Matrix: " +
                             openCVcaller.affineToText(result))

            runningresult = numpy.dot(runningresult, result)
            # transformTargets for display purposes only
            self.transformTargets(runningresult, tilt0targets)
            self.logger.info("Running Matrix: " +
                             openCVcaller.affineToText(runningresult))
            self.logger.info("running result matrix= " + str(
                numpy.asarray(runningresult * 100, dtype=numpy.int8).ravel()))
            imageold = imagenew
            arrayold = arraynew

        ### copied from Acquisition.acquire:
        ## store EMData to DB to prevent referencing errors
        self.publish(imageold['scope'], database=True)
        self.publish(imageold['camera'], database=True)

        ## convert CameraImageData to AcquisitionImageData
        dim = image0['camera']['dimension']
        pixels = dim['x'] * dim['y']
        pixeltype = str(image0['image'].dtype)
        imagedata = leginondata.AcquisitionImageData(
            initializer=imageold,
            preset=image0['preset'],
            label=self.name,
            target=image0['target'],
            list=None,
            emtarget=image0['emtarget'],
            version=0,
            tiltnumber=self.tiltnumber,
            pixels=pixels,
            pixeltype=pixeltype)
        self.setTargets([], 'Peak')
        self.publishDisplayWait(imagedata)

        self.logger.info("FINAL Matrix: " +
                         openCVcaller.affineToText(runningresult))
        return (runningresult, imagedata)
    def trackStage(self, image0, tilt0, tilt, tilt0targets):
        self.logger.info('Running trackStage')
        retriesmax = 15
        retries = retriesmax
        blur = 3
        thresh = 0
        self.logger.info('Returning to state of image0')
        presetname = image0['preset']['name']
        emtarget = image0['emtarget']
        pausetime = self.settings['pause']
        self.presetsclient.toScope(presetname, emtarget)
        ### reset the tilt, just in case user changed it while picking targets
        self.instrument.tem.StagePosition = {'a': tilt0}
        if pausetime > 0.1:
            self.logger.info('Pausing %.1f seconds' %(pausetime,))
            time.sleep(pausetime)

        ### calculate tilt steps
        maxstepsize = radians(self.settings['stepsize'])
        tilts = self.calculateTiltSteps(tilt0, tilt, maxstepsize)
        self.logger.info('Tilts: %s' % ([("%.1f"%degrees(t)) for t in tilts],))

        imageold = image0
        arrayold = numpy.asarray(imageold['image'], dtype=numpy.float32)
        self.setImage(arrayold, 'Image')
        runningresult = numpy.identity(3, numpy.float32)

        # transformTargets for display purposes only
        self.transformTargets(runningresult, tilt0targets)

        #for tilt in tilts:
        ### use while loop so we can backtrack
        i = 0
        while i < len(tilts)-1:
            i+=1
            tilt = float("%.3f"%tilts[i])
            self.logger.info('Going to tilt angle: %.2f' % (degrees(tilt),))
            self.instrument.tem.StagePosition = {'a': tilt}
            is_small_tilt_diff = self.isSmallTiltDifference(tilts,i,tilt0)
            if pausetime > 0.1:
                self.logger.info('Pausing %.1f seconds' %(pausetime,))
                time.sleep(pausetime)
            self.logger.info('Acquire intermediate tilted parent image')
            imagenew = self.acquireCorrectedCameraImageData()
            arraynew = numpy.asarray(imagenew['image'], dtype=numpy.float32)
            self.setImage(arraynew, 'Image')

            if is_small_tilt_diff:
                self.logger.info('Use phase correlation on small tilt')
                result = numpy.array(self.shiftmatrix_maker.register(arrayold, arraynew))
            else:

                print '============ openCV stuff ============'

                self.logger.info('openCV stuff')
                minsize = self.settings['minsize']
                maxsize = self.settings['maxsize']
                openCVcaller.checkArrayMinMax(self, arrayold, arraynew)
                print 'tilt', tilts[i]*180/3.14159
                result = openCVcaller.MatchImages(arrayold, arraynew, blur, thresh)
                self.logger.info("result matrix= "+str(numpy.asarray(result*100, dtype=numpy.int8).ravel()))
                print "RESULT", result

                check = openCVcaller.checkOpenCVResult(self, result, is_small_tilt_diff)
                if check is False:
                    self.logger.warning("openCV failed: redoing tilt %.2f"%(tilt,))
                    if retries:
                        i -= 1
                        retries -= 1
                        if retries <= retriesmax/2:
                            thresh = 1
                            print "THRESH = 1"                         
                        print "retries =", retries, "out of", retriesmax
                    else:
                        print "Tilt openCV FAILED"
                        self.logger.error("openCV failed: giving up")
                        self.instrument.tem.StagePosition = {'a': tilt0}
                        return None, None
                    continue
                else:
                    retries = 0         
                print '============ openCV stuff done ============'

            self.logger.info("result matrix= "+str(numpy.asarray(result*100, dtype=numpy.int8).ravel()))
            self.logger.info( "Inter Matrix: "+openCVcaller.affineToText(result) )

            runningresult = numpy.dot(runningresult, result)
            # transformTargets for display purposes only
            self.transformTargets(runningresult, tilt0targets)
            self.logger.info( "Running Matrix: "+openCVcaller.affineToText(runningresult) )
            self.logger.info("running result matrix= "+str(numpy.asarray(runningresult*100, dtype=numpy.int8).ravel()))
            imageold = imagenew
            arrayold = arraynew

        ### copied from Acquisition.acquire:
        ## store EMData to DB to prevent referencing errors
        self.publish(imageold['scope'], database=True)
        self.publish(imageold['camera'], database=True)

        ## convert CameraImageData to AcquisitionImageData
        dim = image0['camera']['dimension']
        pixels = dim['x'] * dim['y']
        pixeltype = str(image0['image'].dtype)
        imagedata = leginondata.AcquisitionImageData(initializer=imageold, preset=image0['preset'], label=self.name,
            target=image0['target'], list=None, emtarget=image0['emtarget'], 
            version=0, tiltnumber=self.tiltnumber, pixels=pixels, pixeltype=pixeltype)
        self.setTargets([], 'Peak')
        self.publishDisplayWait(imagedata)

        self.logger.info( "FINAL Matrix: "+openCVcaller.affineToText(runningresult) )
        return (runningresult, imagedata)