def load_microscope(npzfile=None, save_settings=False, dummy_stage=True, **kwargs): """Create a microscope object with specified settings. (context manager) This will read microscope settings from a .npz file, and/or from keyword arguments. It will then create the microscope object, and close it at the end of the with statement. Keyword arguments will override settings specified in the file. If save_settings is True, it will attempt to save the microscope's settings at the end of the with block, to the same filename. If save_settings_on_exit is set to a string, it should save instead to that filename. """ settings = {} try: npz = np.load(npzfile) for k in npz: settings[k] = npz[k] except: pass settings.update(kwargs) if "stage_port" in settings: stage_port = settings["stage_port"] del settings["stage_port"] else: stage_port = None # Open the hardware connections with closing(DummyStage() if dummy_stage else OpenFlexureStage(stage_port)) as stage, \ closing(PiCamera(**extract_settings(settings, picamera_init_settings))) as camera: ms = Microscope(camera, stage) for k, v in extract_settings(settings, picamera_later_settings).items(): setattr(ms.camera, k, v) yield ms # The contents of the with block from which we're called happen here if save_settings: if save_settings is True: save_settings = npzfile ms.save_settings(save_settings)
def __init__(self): #defines some camera parameters camera_resolution = (3280, 2464) #camera_resolution = (1024, 768) self.camera = picamera.PiCamera(resolution = camera_resolution) # some initial default values - modified in microscope_config.txt time.sleep(2) config = initialise_config() # automatically determine the port name self.arduino_port = config.detect_arduino_port() self.stage = OpenFlexureStage(self.arduino_port) #self.step = 300 # step of motor movement config.read_config_file() self.camera.shutter_speed = int(config.shutter_speed) self.camera.exposure_mode = 'off' self.camera.awb_mode = config.awb_mode self.camera.awb_gains = (float(config.red_gain), float(config.blue_gain)) self.camera.iso = int(config.iso) self.camera.saturation = int(config.saturation) self.camera.brightness = 50 self.camera.annotate_text_size = int(camera_resolution[0]*0.03) # reasonable ratio for any resolution
import microscope import picamera import data_file from openflexure_stage import OpenFlexureStage import threading import matplotlib.pyplot as plt import matplotlib import data_file import h5py import tweepy import twitter_keys if __name__ == "__main__": with picamera.PiCamera(resolution=( 640, 480)) as camera, OpenFlexureStage('/dev/ttyUSB0') as stage: #authorises the program to acces the twitter account auth = tweepy.OAuthHandler(twitter_keys.consumer_key, twitter_keys.consumer_secret) auth.set_access_token(twitter_keys.access_token, twitter_keys.access_token_secret) api = tweepy.API(auth) N_frames = 100 counter = 0 #loads camera from picamera and set the stage as the arduino, lower resolution can speed up the programme ms = microscope.Microscope(camera, stage) ms.freeze_camera_settings() frame = get_numpy_image(camera, True)
with closing(DummyStage() if dummy_stage else OpenFlexureStage(stage_port)) as stage, \ closing(PiCamera(**extract_settings(settings, picamera_init_settings))) as camera: ms = Microscope(camera, stage) for k, v in extract_settings(settings, picamera_later_settings).items(): setattr(ms.camera, k, v) yield ms # The contents of the with block from which we're called happen here if save_settings: if save_settings is True: save_settings = npzfile ms.save_settings(save_settings) if __name__ == "__main__": with picamera.PiCamera() as camera, \ OpenFlexureStage("/dev/ttyUSB0") as stage: # camera.resolution=(640,480) camera.start_preview() ms = Microscope(camera, stage) ms.freeze_camera_settings(iso=100) camera.shutter_speed = camera.shutter_speed / 4 backlash = 128 for step, n in [(1000, 10), (200, 10), (100, 10), (50, 10)]: dz = (np.arange(n) - (n - 1) / 2.0) * step pos, sharps = ms.autofocus(dz, backlash=backlash) plt.plot(pos, sharps, 'o-')
import numpy as np from scipy import ndimage, signal import sys import time from camera_stuff import get_numpy_image, find_template import microscope import picamera import data_file from openflexure_stage import OpenFlexureStage import h5py from contextlib import closing if __name__ == "__main__": with picamera.PiCamera(resolution = (640, 480)) as camera, \ OpenFlexureStage('/dev/ttyUSB0') as stage, \ closing(data_file.Datafile(filename = "orthogonality_15123.hdf5")) as df: side_length = 4000 points = 10 stage.backlash = 256 camera.start_preview() image = get_numpy_image(camera, greyscale=True).astype(np.float32) background = cv2.GaussianBlur(image, (41, 41), 0) templ8 = (image - background)[100:-100, 100:-100] stage_centre = stage.position
import time from camera_stuff import get_numpy_image, find_template import microscope import picamera import data_file from openflexure_stage import OpenFlexureStage import threading import matplotlib.pyplot as plt import matplotlib import data_file import h5py if __name__ == "__main__": with picamera.PiCamera(resolution=(640, 480), framerate=100) as camera, OpenFlexureStage( '/dev/ttyUSB0') as stage: N_frames = 1000 #loads camera from picamera and set the stage as the arduino, lower resolution can speed up the programme camera.start_preview() #shows preview of camera ms = microscope.Microscope(camera, stage) ms.freeze_camera_settings() frame = get_numpy_image(camera, True) print "Frame is {}".format(frame.shape) #print resolution backlash = 128 #counters backlash stage.move_rel([-backlash, -backlash, -backlash]) stage.move_rel([backlash, backlash, backlash]) #energise motors stage.backlash = backlash
raise ValueError("Error setting output filepath. Valid filepaths should" " either be [creatable] directories, or end with a " "filename that contains '%d' and ends in '.jpg' or '.jpeg'") #run microscope_control.py directly if __name__ == '__main__': pass argv = docopt.docopt(__doc__, options_first=True) stage = OpenFlexureStage('/dev/ttyUSB0') if argv['move']: x, y, z = [int(argv.get(d, 0)) for d in ['<x>', '<y>', '<z>']] print ("moving", x, y, z) stage.move_rel([x, y, z]) elif argv['focus']: stage.focus_rel(int(argv['<z>'])) else: #if argv['control']: def move_stage_with_keyboard(stdscr): stdscr.addstr(0,0,"wasd to move in X/Y, qe for Z\n" "r/f to decrease/increase step.\n" "v/b to start/stop video preview.\n" "i/o to zoom in/out.\n" "t/g to adjust contrast, y/h to adjust brightness.\n" "j to save jpeg file, k to change output path.\n"
from openflexure_stage import OpenFlexureStage import numpy as np import matplotlib.pyplot as plt if __name__ == "__main__": with OpenFlexureStage("COM3") as stage: #with OpenFlexureStage("/dev/ttyUSB1") as stage: gains = stage.light_sensor_gain_values print gains f, axes = plt.subplots(1, len(gains)) for i in range(len(gains)): stage.light_sensor_gain = gains[i] print "Gain is {}".format(stage.light_sensor_gain) #print "Integration time is {} ms".format(stage.light_sensor_integration_time) print "Reading sensor", readings = np.zeros(50) for j in range(len(readings)): readings[j] = stage.light_sensor_intensity print ".", print "done" print "reading {}+/-{}".format(np.mean(readings), np.std(readings)) axes[i].plot(readings) plt.show()
#import libraries import numpy as np from openflexure_stage import OpenFlexureStage import time from contextlib import closing import h5py import data_file if __name__ == "__main__": with OpenFlexureStage('/dev/ttyUSB0') as stage, closing( data_file.Datafile(filename="background.hdf5")) as df: n = 200 output = np.zeros((2, n)) data_gr = df.new_group("data", "A file of data collected") for gain in [1, 25, 428, 9876]: gain_group = df.new_group("Gain", "Measurements for one gain", parent=data_gr) stage.light_sensor_gain = gain data = np.zeros(n) for i in range(n): data[i] = stage.light_sensor_fullspectrum time.sleep(5) mean = np.mean(data) error = np.std(data) print "When gain = %d: \nMean background signal = %d +/- %d \n" % ( gain, mean, error) df.add_data(data, gain_group, "data")
#import libraries import numpy as np import io import sys import time import data_file from openflexure_stage import OpenFlexureStage import threading import matplotlib.pyplot as plt import matplotlib import data_file import h5py if __name__ == "__main__": with OpenFlexureStage('COM3') as stage: i = -1 buffer = np.zeros(50) gains = stage.light_sensor_gain_values plt.ion() f, ax = plt.subplots(1, 1) line = plt.plot(buffer)[0] while True: try: i = (i + 1) % len(buffer) buffer[i] = stage.light_sensor_intensity line.set_ydata(buffer) ax.relim() ax.autoscale_view() f.canvas.draw()
return filepath else: raise ValueError( "Error setting output filepath. Valid filepaths should" " either be [creatable] directories, or end with a " "filename that contains '%d' and ends in '.jpg' or '.jpeg'") #run microscope_control.py directly if __name__ == '__main__': pass argv = docopt.docopt(__doc__, options_first=True) stage = OpenFlexureStage('/dev/ttyUSB0') if argv['move']: x, y, z = [int(argv.get(d, 0)) for d in ['<x>', '<y>', '<z>']] print("moving", x, y, z) stage.move_rel([x, y, z]) elif argv['focus']: stage.focus_rel(int(argv['<z>'])) else: #if argv['control']: def move_stage_with_keyboard(stdscr): stdscr.addstr( 0, 0, "wasd to move in X/Y, qe for Z\n" "r/f to decrease/increase step.\n" "v/b to start/stop video preview.\n" "i/o to zoom in/out.\n"
class camera_control(): def __init__(self): #defines some camera parameters camera_resolution = (3280, 2464) #camera_resolution = (1024, 768) self.camera = picamera.PiCamera(resolution = camera_resolution) # some initial default values - modified in microscope_config.txt time.sleep(2) config = initialise_config() # automatically determine the port name self.arduino_port = config.detect_arduino_port() self.stage = OpenFlexureStage(self.arduino_port) #self.step = 300 # step of motor movement config.read_config_file() self.camera.shutter_speed = int(config.shutter_speed) self.camera.exposure_mode = 'off' self.camera.awb_mode = config.awb_mode self.camera.awb_gains = (float(config.red_gain), float(config.blue_gain)) self.camera.iso = int(config.iso) self.camera.saturation = int(config.saturation) self.camera.brightness = 50 self.camera.annotate_text_size = int(camera_resolution[0]*0.03) # reasonable ratio for any resolution def stage_library(self, command, direction): """Use this class from kivy interface to use motors, change picamera etc. in case there is no stage connected, use the exception to avoid crash""" try: if command == 'move_x': if direction == '+': self.stage.move_rel([-self.step,0,0]) else: self.stage.move_rel([self.step,0,0]) if command == 'move_y': if direction == '+': self.stage.move_rel([0,self.step,0]) else: self.stage.move_rel([0,-self.step,0]) if command == 'move_z': if direction == '+': self.stage.move_rel([0,0,self.step]) else: self.stage.move_rel([0,0,-self.step]) if command == 'change_self.step': if direction == '+': self.step = self.step*2 else: self.step = self.step/2 except IOError: # When there is no actual motorised stage connected, do nothing pass def camera_library(self, argv, *value): "Use this function from kivy interface to change picamera etc." if argv == 'start_preview': self.camera.start_preview() elif argv == 'stop_preview': self.camera.stop_preview() elif argv == 'reduced_size_preview': self.camera.start_preview(fullscreen = False, window = value[0]) elif argv == 'fullscreen_preview': self.camera.start_preview(fullscreen = True) elif argv == 'set_contrast': self.camera.contrast = int(value[0]) elif argv == 'set_brightness': self.camera.brightness = int(value[0]) elif argv == 'set_white_balance': self.camera.awb_gains = (value[0],value[1]) elif argv == 'set_iso': self.camera.iso = int(value[0]) elif argv == 'set_shutter_speed': self.camera.shutter_speed = int(value[0]) elif argv == 'set_saturation': self.camera.saturation = int(value[0]) elif argv == 'change_annotation': self.camera.annotate_text = value[0] # 'save_image' cannot be the last elif for some reason? elif argv == 'save_image': # remove any text overlay folder = value[0] if not os.path.isdir(folder): os.mkdir(folder) image_filepath = value[1] # format can be 'jpg', 'jpeg', 'raw', 'png' file_format = value[2] while True: # if there is a file with same name, add a -new behind file name if os.path.isfile(image_filepath+'.jpeg') or os.path.isfile(image_filepath+'.png'): image_filepath = image_filepath + '-new.' else: break if file_format == 'raw': self.camera.capture(image_filepath + '.jpeg', format = 'jpeg', bayer = True) elif file_format == 'png': self.camera.capture(image_filepath + '.png', format = 'png') else: self.camera.capture(image_filepath + '.jpeg', format = 'jpeg') time.sleep(2) self.camera.annotate_text = "Image saved as {}".format(image_filepath) elif argv == 'zoom_in' or 'zoom_out': if argv == 'zoom_in': self.fov = self.fov*3/4 elif argv == 'zoom_out' and self.fov < 1: self.fov = self.fov*4/3 self.camera.zoom = (0.5-self.fov/2, 0.5-self.fov/2, self.fov, self.fov) self.camera.annotate_text = 'magnification: {0:.2f}X'.format(1/self.fov)