├── openflexure_microscope ├── utilities │ ├── __init__.py │ ├── recalibrate_openloop.py │ └── recalibrate.py ├── __init__.py ├── characterisation │ └── example_images │ │ └── example_usaf.jpg ├── __main__.py ├── keyboard_control.py └── microscope.py ├── microscope_settings.npz ├── microscope_characterisation ├── example_images │ ├── example_usaf.jpg │ ├── example_h_edge.jpg │ └── example_v_edge.jpg ├── measure_edge_images.py ├── print_awb_gains.py ├── acquire_zstack.py ├── measure_distortion.py ├── scan_edge.py └── README.md ├── tests ├── test_reconstruction.py └── test_picamera.py ├── .gitignore ├── setup.py ├── README.rst └── LICENSE /openflexure_microscope/utilities/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /openflexure_microscope/__init__.py: -------------------------------------------------------------------------------- 1 | from .microscope import Microscope, load_microscope 2 | __version__ = "0.1.2" 3 | -------------------------------------------------------------------------------- /microscope_settings.npz: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rwb27/openflexure_microscope_software/HEAD/microscope_settings.npz -------------------------------------------------------------------------------- /microscope_characterisation/example_images/example_usaf.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rwb27/openflexure_microscope_software/HEAD/microscope_characterisation/example_images/example_usaf.jpg -------------------------------------------------------------------------------- /microscope_characterisation/example_images/example_h_edge.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rwb27/openflexure_microscope_software/HEAD/microscope_characterisation/example_images/example_h_edge.jpg -------------------------------------------------------------------------------- /microscope_characterisation/example_images/example_v_edge.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rwb27/openflexure_microscope_software/HEAD/microscope_characterisation/example_images/example_v_edge.jpg -------------------------------------------------------------------------------- /openflexure_microscope/characterisation/example_images/example_usaf.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rwb27/openflexure_microscope_software/HEAD/openflexure_microscope/characterisation/example_images/example_usaf.jpg -------------------------------------------------------------------------------- /microscope_characterisation/measure_edge_images.py: -------------------------------------------------------------------------------- 1 | """ 2 | A script to take a series of images of an edge, either side of 3 | focus, to evaluate the resolution of the microscope. 4 | 5 | (c) Richard Bowman 2017, released under GPL v3 6 | """ 7 | import microscope 8 | 9 | -------------------------------------------------------------------------------- /microscope_characterisation/print_awb_gains.py: -------------------------------------------------------------------------------- 1 | """ 2 | A script to print the current AWB gains of the Pi Camera 3 | """ 4 | import picamera 5 | 6 | 7 | if __name__ == "__main__": 8 | with picamera.PiCamera(resolution=microscope.picam2_full_res) as camera: 9 | camera.start_preview() 10 | 11 | time.sleep(3) 12 | print "AWB Gains:" 13 | print camera.awb_gains 14 | 15 | -------------------------------------------------------------------------------- /tests/test_reconstruction.py: -------------------------------------------------------------------------------- 1 | import microscope 2 | import picamera 3 | import numpy as np 4 | import matplotlib.pyplot as plt 5 | import time 6 | #resolution=(3280,2464) 7 | #m = microscope.Microscope(picamera.PiCamera(resolution=(640,480)), None) 8 | m = microscope.Microscope(picamera.PiCamera(resolution=(3280/1,2464/1)), None) 9 | m.cam.start_preview() 10 | time.sleep(2) 11 | image = m.rgb_image() 12 | m.cam.stop_preview() 13 | 14 | plt.figure() 15 | plt.imshow(image) 16 | plt.figure() 17 | plt.imshow(microscope.decimate_to((100,100),image)) 18 | plt.show() 19 | -------------------------------------------------------------------------------- /tests/test_picamera.py: -------------------------------------------------------------------------------- 1 | # simple test jig for picamera 2 | 3 | import picamera 4 | import cv2 5 | import numpy as np 6 | import scipy 7 | from scipy import ndimage 8 | import os 9 | import sys 10 | import time 11 | import matplotlib.pyplot as plt 12 | from openflexure_stage import OpenFlexureStage 13 | import microscope 14 | 15 | if __name__ == "__main__": 16 | with picamera.PiCamera(sensor_mode=3, resolution=(3280,2464)) as camera: 17 | #with picamera.PiCamera() as camera: 18 | camera.start_preview() 19 | ms = microscope.Microscope(camera, None) 20 | time.sleep(3) 21 | ms.freeze_camera_settings(iso=100) 22 | # camera.shutter_speed = camera.shutter_speed / 4 23 | time.sleep(1) 24 | camera.capture("test_image0.jpg") 25 | time.sleep(0.5) 26 | camera.capture("test_image1.jpg") 27 | camera.capture("test_image2.jpg") 28 | time.sleep(0.5) 29 | 30 | 31 | #plt.show() 32 | 33 | print "Done :)" 34 | 35 | -------------------------------------------------------------------------------- /openflexure_microscope/__main__.py: -------------------------------------------------------------------------------- 1 | from .keyboard_control import parse_command_line_arguments 2 | from .keyboard_control import control_microscope_with_keyboard 3 | from .utilities.recalibrate import generate_lens_shading_table_closed_loop 4 | import argparse 5 | 6 | def main(): 7 | parser = argparse.ArgumentParser(description="Control an Openflexure Microscope") 8 | parser.add_argument("--recalibrate", action="store_true", 9 | help="Reset the microscope's settings and regenerate the lens shading correction table. Saves to ./microscope_settings.npz.") 10 | parser.add_argument("--no_stage", action="store_true", 11 | help="Do not attempt to connect to a motor controller. Use this option if you are moving the microscope by hand.") 12 | parser.add_argument("--output", help="directory or filepath (with %%d wildcard) for saved images", default="~/Desktop/images") 13 | parser.add_argument("--settings_file", help="File where the microscope settings are stored.", default="microscope_settings.npz") 14 | args = parser.parse_args() 15 | if args.recalibrate: 16 | generate_lens_shading_table_closed_loop(args.settings_file) 17 | else: 18 | control_microscope_with_keyboard(output=args.output, dummy_stage=args.no_stage, settings_file=args.settings_file) 19 | 20 | if __name__ == '__main__': 21 | main() 22 | 23 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # Virtual environments 29 | venvs/ 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | .hypothesis/ 51 | 52 | # Translations 53 | *.mo 54 | *.pot 55 | 56 | # Django stuff: 57 | *.log 58 | local_settings.py 59 | 60 | # Flask stuff: 61 | instance/ 62 | .webassets-cache 63 | 64 | # Scrapy stuff: 65 | .scrapy 66 | 67 | # Sphinx documentation 68 | docs/_build/ 69 | 70 | # PyBuilder 71 | target/ 72 | 73 | # Jupyter Notebook 74 | .ipynb_checkpoints 75 | 76 | # pyenv 77 | .python-version 78 | 79 | # celery beat schedule file 80 | celerybeat-schedule 81 | 82 | # SageMath parsed files 83 | *.sage.py 84 | 85 | # dotenv 86 | .env 87 | 88 | # virtualenv 89 | .venv 90 | venv/ 91 | ENV/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | __author__ = 'Richard Bowman' 2 | 3 | from setuptools import setup, find_packages 4 | from codecs import open 5 | from os import path 6 | import re 7 | 8 | here = path.abspath(path.dirname(__file__)) 9 | 10 | # Get the long description from the README file 11 | with open(path.join(here, 'README.rst'), encoding='utf-8') as f: 12 | long_description = f.read() 13 | 14 | def find_version(): 15 | """Determine the version based on __init__.py""" 16 | with open(path.join(here, "openflexure_microscope", "__init__.py"), 'r') as f: 17 | init_py = f.read() 18 | version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", init_py, re.M) 19 | if version_match: 20 | return version_match.group(1) 21 | raise RuntimeError("Couldn't parse version string from __init__.py") 22 | 23 | version = find_version() 24 | 25 | setup(name = 'openflexure_microscope', 26 | version = version, 27 | description = 'Control scripts for the OpenFlexure Microscope', 28 | long_description = long_description, 29 | url = 'http://www.github.com/rwb27/openflexure_microscope_software', 30 | author = 'Richard Bowman', 31 | author_email = 'r.w.bowman@bath.ac.uk', 32 | download_url = 'https://github.com/rwb27/openflexure_microscope_software/archive/{}.tar.gz'.format(version), 33 | packages = find_packages(), 34 | keywords = ['arduino','serial','microscope'], 35 | zip_safe = True, 36 | classifiers = [ 37 | 'Development Status :: 4 - Beta', 38 | 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 39 | 'Programming Language :: Python :: 2.7' 40 | ], 41 | install_requires = [ 42 | 'pyserial', 43 | 'future', 44 | 'openflexure_stage', 45 | 'readchar', 46 | 'numpy', 47 | 'scipy', 48 | 'matplotlib', 49 | 'picamera', 50 | ], 51 | dependency_links = [ # The aim is to be backwards-compatible; the lens shading is not required 52 | #'https://github.com/rwb27/picamera/tarball/lens-shading' 53 | ], 54 | entry_points = { 55 | 'console_scripts': [ 56 | 'openflexure_microscope = openflexure_microscope.__main__:main' 57 | ] 58 | }, 59 | ) 60 | 61 | -------------------------------------------------------------------------------- /microscope_characterisation/acquire_zstack.py: -------------------------------------------------------------------------------- 1 | """ 2 | A script to take a series of images of an edge, scanned across the FoV, 3 | in order to measure distortion of the field. 4 | 5 | (c) Richard Bowman 2017, released under GPL v3 6 | """ 7 | import picamera 8 | import cv2 9 | import numpy as np 10 | import scipy 11 | from scipy import ndimage 12 | import os 13 | import sys 14 | import time 15 | import matplotlib.pyplot as plt 16 | from openflexure_stage import OpenFlexureStage 17 | import microscope 18 | 19 | 20 | def dz_array(step, n): 21 | """A list of Z displacements with a given number and spacing""" 22 | return (np.arange(n) - (n-1)/2.0) * step 23 | 24 | def log_dz_array(min_step, log_factor, n): 25 | """A list of Z displacements with a given number and spacing""" 26 | half_steps = min_step * log_factor**(np.arange(np.floor(n/2))) 27 | half_dz = np.cumsum(half_steps) 28 | if n % 2 == 1: 29 | return np.concatenate([-half_dz[::-1], [0], half_dz]) 30 | else: 31 | half_dz[0] /= 2 32 | return np.concatenate([-half_dz[::-1], half_dz]) 33 | 34 | 35 | if __name__ == "__main__": 36 | try: 37 | output_dir = sys.argv[1] 38 | z_shift = int(sys.argv[2]) 39 | n_shifts = int(sys.argv[3]) 40 | except IndexError: 41 | output_dir = "--help" 42 | 43 | if "--help" in output_dir: 44 | print "Usage: acquire_zstack.py " 45 | exit(0) 46 | os.makedirs(output_dir) 47 | 48 | with picamera.PiCamera(resolution=microscope.picam2_full_res) as camera, \ 49 | OpenFlexureStage("/dev/ttyUSB0") as stage: 50 | camera.start_preview() 51 | stage.write("ramp_time 500000") 52 | ms = microscope.Microscope(camera, stage) 53 | time.sleep(3) 54 | ms.freeze_camera_settings(iso=100) 55 | camera.shutter_speed = camera.shutter_speed / 2 56 | 57 | time.sleep(1) 58 | #plt.imshow(ms.rgb_image()) 59 | #ms.cam.stop_preview() 60 | #plt.show() 61 | #ms.cam.start_preview() 62 | 63 | stage.backlash=128 64 | 65 | #camera.zoom=(0.4,0.4,0.2,0.2) 66 | #ms.autofocus(log_dz_array(100, 1.5, 11), backlash=backlash) 67 | #camera.zoom=(0.0,0.0,1.0,1.0) 68 | time.sleep(1) 69 | pos = stage.position 70 | 71 | ii = np.arange(n_shifts) - (n_shifts - 1.0)/2.0 # an array centred on zero 72 | scan_points = ii[:, np.newaxis] * np.array([0,0,z_shift])[np.newaxis,:] 73 | 74 | for i in ms.scan_linear(scan_points): 75 | time.sleep(1) 76 | camera.capture(os.path.join(output_dir,"zstack_%03d_x%d_y%d_z%d.jpg" % ((i,) + tuple(stage.position))), use_video_port=False) 77 | time.sleep(0.5) 78 | 79 | 80 | #plt.show() 81 | 82 | print "Done :)" 83 | 84 | -------------------------------------------------------------------------------- /microscope_characterisation/measure_distortion.py: -------------------------------------------------------------------------------- 1 | """ 2 | A script to take a series of images of an edge, scanned across the FoV, 3 | in order to measure distortion of the field. 4 | 5 | (c) Richard Bowman 2017, released under GPL v3 6 | """ 7 | import picamera 8 | import cv2 9 | import numpy as np 10 | import scipy 11 | from scipy import ndimage 12 | import os 13 | import sys 14 | import time 15 | import matplotlib.pyplot as plt 16 | from openflexure_stage import OpenFlexureStage 17 | import microscope 18 | 19 | 20 | def dz_array(step, n): 21 | """A list of Z displacements with a given number and spacing""" 22 | return (np.arange(n) - (n-1)/2.0) * step 23 | 24 | def log_dz_array(min_step, log_factor, n): 25 | """A list of Z displacements with a given number and spacing""" 26 | half_steps = min_step * log_factor**(np.arange(np.floor(n/2))) 27 | half_dz = np.cumsum(half_steps) 28 | if n % 2 == 1: 29 | return np.concatenate([-half_dz[::-1], [0], half_dz]) 30 | else: 31 | half_dz[0] /= 2 32 | return np.concatenate([-half_dz[::-1], half_dz]) 33 | 34 | 35 | if __name__ == "__main__": 36 | try: 37 | output_dir = sys.argv[1] 38 | xy_shift = np.array([sys.argv[2], sys.argv[3], 0], dtype=np.int) 39 | n_shifts = int(sys.argv[4]) 40 | except IndexError: 41 | output_dir = "--help" 42 | 43 | if "--help" in output_dir: 44 | print "Usage: scan_edge.py " 45 | print "If x and y shift are specified, we do the scan 3 times" 46 | print "once at the present position, once at -shift, once at +shift." 47 | exit(0) 48 | os.makedirs(output_dir) 49 | 50 | with picamera.PiCamera(resolution=microscope.picam2_full_res) as camera, \ 51 | OpenFlexureStage("/dev/ttyUSB0") as stage: 52 | camera.start_preview() 53 | ms = microscope.Microscope(camera, stage) 54 | time.sleep(3) 55 | ms.freeze_camera_settings(iso=320) 56 | #camera.shutter_speed = camera.shutter_speed / 2 57 | 58 | time.sleep(1) 59 | #plt.imshow(ms.rgb_image()) 60 | #ms.cam.stop_preview() 61 | #plt.show() 62 | #ms.cam.start_preview() 63 | 64 | stage.backlash=128 65 | 66 | #camera.zoom=(0.4,0.4,0.2,0.2) 67 | #ms.autofocus(log_dz_array(100, 1.5, 11), backlash=backlash) 68 | #camera.zoom=(0.0,0.0,1.0,1.0) 69 | time.sleep(1) 70 | pos = stage.position 71 | 72 | ii = np.arange(n_shifts) - (n_shifts - 1.0)/2.0 # an array centred on zero 73 | scan_points = ii[:, np.newaxis] * xy_shift[np.newaxis, :] 74 | 75 | for i in ms.scan_linear(scan_points): 76 | time.sleep(1) 77 | camera.capture(os.path.join(output_dir,"edge_zstack_%03d_x%d_y%d_z%d.jpg" % ((i,) + tuple(stage.position))), use_video_port=False) 78 | time.sleep(0.5) 79 | 80 | 81 | #plt.show() 82 | 83 | print "Done :)" 84 | 85 | -------------------------------------------------------------------------------- /microscope_characterisation/scan_edge.py: -------------------------------------------------------------------------------- 1 | """ 2 | A script to take a series of images of an edge, either side of 3 | focus, to evaluate the resolution of the microscope. 4 | 5 | (c) Richard Bowman 2017, released under GPL v3 6 | """ 7 | import picamera 8 | import cv2 9 | import numpy as np 10 | import scipy 11 | from scipy import ndimage 12 | import os 13 | import sys 14 | import time 15 | import matplotlib.pyplot as plt 16 | from openflexure_stage import OpenFlexureStage 17 | import microscope 18 | 19 | 20 | def dz_array(step, n): 21 | """A list of Z displacements with a given number and spacing""" 22 | return (np.arange(n) - (n-1)/2.0) * step 23 | 24 | def log_dz_array(min_step, log_factor, n): 25 | """A list of Z displacements with a given number and spacing""" 26 | half_steps = min_step * log_factor**(np.arange(np.floor(n/2))) 27 | half_dz = np.cumsum(half_steps) 28 | if n % 2 == 1: 29 | return np.concatenate([-half_dz[::-1], [0], half_dz]) 30 | else: 31 | half_dz[0] /= 2 32 | return np.concatenate([-half_dz[::-1], half_dz]) 33 | 34 | 35 | if __name__ == "__main__": 36 | try: 37 | output_dir = sys.argv[1] 38 | except IndexError: 39 | output_dir = "--help" 40 | if "--help" in output_dir: 41 | print "Usage: scan_edge.py " 42 | print "If x and y shift are specified, we do the scan 3 times" 43 | print "once at the present position, once at -shift, once at +shift." 44 | exit(0) 45 | os.makedirs(output_dir) 46 | 47 | try: 48 | xy_shift = np.array([sys.argv[2], sys.argv[3], 0], dtype=np.int) 49 | except IndexError: 50 | xy_shift = None 51 | 52 | with picamera.PiCamera(resolution=microscope.picam2_full_res) as camera, \ 53 | OpenFlexureStage("/dev/ttyUSB0") as stage: 54 | camera.start_preview() 55 | ms = microscope.Microscope(camera, stage) 56 | time.sleep(3) 57 | ms.freeze_camera_settings(iso=320) 58 | #camera.shutter_speed = camera.shutter_speed / 2 59 | 60 | time.sleep(1) 61 | #plt.imshow(ms.rgb_image()) 62 | #ms.cam.stop_preview() 63 | #plt.show() 64 | #ms.cam.start_preview() 65 | 66 | stage.backlash=128 67 | 68 | #camera.zoom=(0.4,0.4,0.2,0.2) 69 | # ms.autofocus(log_dz_array(40, 1.5, 11)) 70 | #camera.zoom=(0.0,0.0,1.0,1.0) 71 | time.sleep(1) 72 | pos = np.array(stage.position) 73 | if xy_shift is not None: 74 | starting_positions = [pos - xy_shift, pos, pos + xy_shift] 75 | foldernames = ["neg_%d_%d" % tuple(xy_shift[:2]), "centre", "pos_%d_%d" % tuple(xy_shift[:2])] 76 | else: 77 | starting_positions = [pos] 78 | foldernames = ["centre"] 79 | 80 | for startpos, fname in zip(starting_positions, foldernames): 81 | os.makedirs(os.path.join(output_dir, fname)) 82 | if np.any(startpos != stage.position): 83 | stage.move_abs(startpos) 84 | 85 | # ms.autofocus(dz_array(100,10), backlash=backlash) 86 | 87 | for i in ms.scan_z(log_dz_array(30,1.2, 15)): 88 | time.sleep(3) 89 | camera.capture(os.path.join(output_dir,fname,"edge_zstack_raw_%03d_x%d_y%d_z%d.jpg" % ((i,) + tuple(stage.position))), use_video_port=False, bayer=True) 90 | camera.capture(os.path.join(output_dir,fname,"edge_zstack_%03d_x%d_y%d_z%d.jpg" % ((i,) + tuple(stage.position))), use_video_port=False) 91 | time.sleep(0.5) 92 | stage.move_rel(np.array(pos) - np.array(stage.position)) 93 | 94 | 95 | #plt.show() 96 | 97 | print "Done :)" 98 | 99 | -------------------------------------------------------------------------------- /openflexure_microscope/utilities/recalibrate_openloop.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | from .. import microscope 3 | import picamera.array 4 | import picamera 5 | import numpy as np 6 | import time 7 | import sys 8 | 9 | 10 | def recalibrate_microscope(output_fname="microscope_settings.npz"): 11 | """Acquire a raw image, and use it to recalculate the lens shading table. 12 | 13 | All microscope settings will be reset, a few seconds of auto-exposure will 14 | be run, then the new settings will be saved to the output file along with a 15 | lens shading table that makes the image, as measured, roughly white. 16 | """ 17 | # Start by loading the raw image from the Pi camera. This creates a ``picamera.PiBayerArray``. 18 | with picamera.PiCamera() as cam: 19 | lens_shading_table = np.zeros(cam._lens_shading_table_shape(), dtype=np.uint8) + 32 20 | max_res = cam.MAX_RESOLUTION 21 | with microscope.load_microscope(lens_shading_table=lens_shading_table, 22 | resolution=max_res) as ms: 23 | ms.camera.start_preview(resolution=(1080*4/3, 1080)) 24 | ms.freeze_camera_settings() 25 | pi_bayer_array = picamera.array.PiBayerArray(ms.camera) 26 | ms.camera.capture(pi_bayer_array, format="jpeg", bayer=True) 27 | settings = ms.settings_dict() 28 | bayer_array_array = pi_bayer_array.array 29 | for k in settings: 30 | print("{}: {}".format(k, settings[k])) 31 | 32 | # The bayer data is split into colour channels - I sum over these 33 | # to avoid confusion and get closer to an array that represents what 34 | # the camera actually measures, i.e. one number = one photodetector. 35 | bayer_data = bayer_array_array.sum(axis=2) #16-bit bayer data 36 | # We need to figure out which pixels to assign to which channels 37 | bayer_pattern = [(i//2, i%2) for i in range(4)] 38 | full_resolution = bayer_data.shape 39 | table_resolution = [(r // 64) + 1 for r in full_resolution] 40 | lens_shading = np.zeros([4] + table_resolution, dtype=np.float) 41 | 42 | for i, offset in enumerate(bayer_pattern): 43 | # We simplify life by dealing with only one channel at a time. 44 | image_channel = bayer_data[offset[0]::2, offset[1]::2] 45 | iw, ih = image_channel.shape 46 | ls_channel = lens_shading[i,:,:] 47 | lw, lh = ls_channel.shape 48 | # The lens shading table is rounded **up** in size to 1/64th of the size of 49 | # the image. Rather than handle edge images separately, I'm just going to 50 | # pad the image by copying edge pixels, so that it is exactly 32 times the 51 | # size of the lens shading table (NB 32 not 64 because each channel is only 52 | # half the size of the full image - remember the Bayer pattern... This 53 | # should give results very close to 6by9's solution, albeit considerably 54 | # less computationally efficient! 55 | padded_image_channel = np.pad(image_channel, 56 | [(0, lw*32 - iw), (0, lh*32 - ih)], 57 | mode="edge") # Pad image to the right and bottom 58 | print("Channel shape: {}x{}, shading table shape: {}x{}, after padding {}".format(iw,ih,lw*32,lh*32,padded_image_channel.shape)) 59 | # Next, fill the shading table (except edge pixels). Please excuse the 60 | # for loop - I know it's not fast but this code needn't be! 61 | box = 3 # We average together a square of this side length for each pixel. 62 | # NB this isn't quite what 6by9's program does - it averages 3 pixels 63 | # horizontally, but not vertically. 64 | for dx in np.arange(box) - box//2: 65 | for dy in np.arange(box) - box//2: 66 | ls_channel[:,:] += padded_image_channel[16+dx::32,16+dy::32] 67 | ls_channel /= box**2 68 | # The original C code written by 6by9 normalises to the central 64 pixels in each channel. 69 | #ls_channel /= np.mean(image_channel[iw//2-4:iw//2+4, ih//2-4:ih//2+4]) 70 | # I have had better results just normalising to the maximum: 71 | ls_channel /= np.max(ls_channel) 72 | # NB the central pixel should now be *approximately* 1.0 (may not be exactly 73 | # due to different averaging widths between the normalisation & shading table) 74 | # For most sensible lenses I'd expect that 1.0 is the maximum value. 75 | # NB ls_channel should be a "view" of the whole lens shading array, so we don't 76 | # need to update the big array here. 77 | # What we actually want to calculate is the gains needed to compensate for the 78 | # lens shading - that's 1/lens_shading_table_float as we currently have it. 79 | gains = 32.0/lens_shading # 32 is unity gain 80 | gains[gains > 255] = 255 # clip at 255, maximum gain is 255/32 81 | gains[gains < 32] = 32 # clip at 32, minimum gain is 1 (is this necessary?) 82 | lens_shading_table = gains.astype(np.uint8) 83 | # Finally, save the results in a numpy zip file. 84 | settings['lens_shading_table'] = lens_shading_table 85 | np.savez(output_fname, **settings) 86 | print("Lens shading table written to {}".format(output_fname)) 87 | print("Using dev version") 88 | with microscope.load_microscope(output_fname) as ms: 89 | ms.camera.start_preview(resolution=(1080*4//3, 1080)) 90 | time.sleep(3) 91 | 92 | 93 | if __name__ == '__main__': 94 | try: 95 | output_fname = sys.argv[1] 96 | except: 97 | output_fname = "microscope_settings.npz" 98 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | openflexure_microscope_software 2 | =============================== 3 | Python module to run the OpenFlexure Microscope 4 | 5 | This repository contains the scripts that run the openflexure microscope. The bulk of the useful code is contained in the Python module ``openflexure_microscope``, though there are some control scripts for characterisation experiments that currently live in a separate folder. These will be integrated into the main control program in due course. 6 | 7 | Installation 8 | ------------ 9 | Before you start 10 | ~~~~~~~~~~~~~~~~ 11 | The microscope software can be installed using `pip`, which is now much simpler thanks to the absolutely brilliant PiWheels_. If you are using the latest Raspbian image (October 2018) this should be set up for you already. If not, you just need to add a line to ``/etc/pip.conf`` (see the PiWheels_ web page for instructions). You will need a working internet connection for the commands below to work. 12 | 13 | If you haven't previously used ``numpy`` or ``scipy`` you may need to install some numerical libraries. Open up a command prompt window and type:: 14 | 15 | sudo apt-get install libatlas-base-dev libjasper-dev 16 | 17 | You will also need to `set up the camera`_ and, ideally, increase the GPU memory split to 256Mb, by running ``sudo raspi-config``. You should first navigate to "interfacing options" and then "camera", and second you should choose "advanced options" and "memory split" to enter 256Mb. You will be asked to restart when you're done. 18 | 19 | We recommend installing in a virtual environment, so that the microscope software doesn't interfere with your system Python distribution. You can do this with:: 20 | 21 | $ sudo apt install virtualenv python3-virtualenv -y 22 | $ virtualenv -p /usr/bin/python3 microscope 23 | $ source microscope/bin/activate 24 | 25 | Whenever you want to use the microscope, you should first activate the environament by typing ``source microscope/bin/activate``. You should see the command prompt change, showing you're using the virtual environment. When you are done, type ``deactivate`` to leave the virtual environment and switch back to using your system's Python installation. 26 | 27 | Download and install 28 | ~~~~~~~~~~~~~~~~~~~~ 29 | You should now switch to your virtual environment and download and install the microscope software (skip the ``source activate`` line if you are not using a virtual environment):: 30 | 31 | source microscope/bin/activate 32 | 33 | wget https://github.com/rwb27/openflexure_nano_motor_controller/archive/master.zip 34 | pip install master.zip 35 | rm master.zip 36 | 37 | wget https://github.com/rwb27/openflexure_microscope_software/archive/master.zip 38 | pip install master.zip 39 | rm master.zip 40 | 41 | This will, by default, ensure you have the dependencies installed, including ``picamera``. To use some features such as lens shading correction, you'll need to install my fork of `picamera` (at least until lens shading is incorporated upstream):: 42 | 43 | wget https://github.com/rwb27/picamera/archive/lens-shading.zip 44 | pip install lens-shading.zip 45 | rm lens-shading.zip 46 | 47 | If your version of Raspbian is older than March 2018, you might not have the latest firmware - this is optional, but it allows you to to get full manual control of the camera (specifically to set gains and lens shading). You can update your firmware using ``sudo rpi-update stable`` if you have ``rpi-update`` installed, and ``sudo apt-get install rpi-update`` if not. 48 | 49 | Once you have installed the module, you can run an interactive microscope control program by running the command ``openflexure_microscope`` in the terminal (see below). You can safely skip the installation of my forked ``picamera`` library, but you will get a warning and some features won't work. If you've not used your camera before, you may need to enable the camera module using ``sudo raspi-config`` and choosing "interfacing options" then "enable/disable camera". You will need to reboot afterwards. 50 | 51 | Usage 52 | ----- 53 | If you are using a virtual environment as recommended above, you'll need to switch to that environment first, then run the microscope software:: 54 | 55 | source microscope/bin/activate 56 | openflexure_microscope --help 57 | openflexure_microscope 58 | 59 | The module installs a command-line script, so you can run ``openflexure_microscope`` to start an interactive control program, or ``openflexure_microscope --help`` to see options. You can disable the motor controller by running ``openflexure_microscope --no_stage`` to run the software for the camera, without support for a motorised stage. 60 | 61 | To recalibrate the microscope (which includes generating a new lens shading function), use ``openflexure_microscope --recalibrate``. This requires you to first set the microscope up so that it is producing the most uniform image possible (i.e. the condenser lens must be properly aligned, and there must either be no sample present, or the sample must be well out of focus so it is not visible). The camera will start up and run for a few seconds, then the lens shading table will be adjusted to make the image uniform, and the camera will run for another few seconds - the image at this point should be uniform. Calibration settings (including lens shading and gain, etc.) will be saved to a file called ``microscope_settings.npz`` in the current directory, and this will be loaded by the interactive script the next time it is run. 62 | 63 | Development 64 | ----------- 65 | If you want to be able to modify the scripts, instead of installing with ``python setup.py install``, use ``python setup.py develop``. This leaves the scripts in the folder where they have been downloaded, but still links them into your system's Python path. That will allow you to run them as normal, but makes them easier to edit. Don't forget to commit your changes to Github - this may be easier if you first fork the repository on Github, then clone and install your copy of it. This is relatively simple: first, click the "fork" button at the top right of this repository's page - that will create a repository in your account. Next, go to that repository, and copy the URL from the "clone or download" link. It should look like ``https://github.com/<>/openflexure_microscope_software.git`` where ``<>`` is replaced with your username on GitHub. Then, replace my URL with yours, and run the same commands:: 66 | 67 | git clone https://github.com/<>/openflexure_microscope_software.git 68 | cd openflexure_microscope_software 69 | python setup.py develop 70 | 71 | .. _PiWheels: https://www.piwheels.org/ 72 | .. _`set up the camera`: https://www.raspberrypi.org/documentation/configuration/camera.md 73 | -------------------------------------------------------------------------------- /microscope_characterisation/README.md: -------------------------------------------------------------------------------- 1 | # Microscope optical calibration scripts 2 | 3 | **The scripts in this folder are now mostly defunct - use the image stack feature in the interactive mode of openflexure_microscope to acquire the sequences of images instead.** 4 | 5 | The scripts in this folder take a series of measurements that can be used to characterise the optical performance of a microscope. For details of what parameters are measured and how the images are analysed, see the [usaf analysis repository](https://github.com/rwb27/usaf_analysis/). In brief, it should measure resolution, field curvature, field distortion, and (if you use a USAF target) magnification. To download these scripts without cloning the repository, use the "raw" links as described in my [wiki article](https://github.com/rwb27/openflexure_microscope/wiki/Downloading-STL-files-from-GitHub). 6 | 7 | ## Controlling the Raspberry Pi 8 | You can plug in a monitor and keyboard to the Raspberry pi and run it normally, or you can SSH in and use the keyboard on your laptop. NB if you use SSH, the images are still displayed on the Raspberry Pi, so you still need a monitor attached - just not a keyboard. If you're using SSH, it works best if the Raspberry Pi connects to or creates a WiFi network when it starts up. 9 | 10 | In the case of the WaterScope image, you can control it with the following steps: 11 | * Download and install [PuTTY](https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html) (google it...) 12 | * Download and install [WinSCP](https://winscp.net/eng/download.php) to copy files across 13 | * Turn on the pi 14 | * Connect to waterscope_wifi (password waterscope) 15 | * Go to http://10.0.0.1/html/ in a web browser and click "stop" 16 | * Open PuTTY, enter 10.0.0.1 as the address, and click "connect" 17 | 18 | ## Calibration protocol 19 | This is a simple protocol to acquire lots of images of edges, which can then be used to recover the resolution and distortion of a microscope. It is designed to use a USAF calibration target, but if that's not available, any slide with horizontal and vertical edges will work. This script should be run on a Raspberry Pi connected to an [Openflexure Microscope](https://github.com/rwb27/openflexure_microscope), using the ["Sangaboard" motor controller](https://github.com/rwb27/openflexure_nano_motor_controller). 20 | 21 | From an SSH terminal or from the command line, change to the directory where the control scripts are located, for example: 22 | ```bash 23 | cd microscope_rwb 24 | ``` 25 | To control the microscope (to move the stage interactively, take pictures, etc.) type: 26 | ```bash 27 | python microscope_control.py 28 | ``` 29 | It will display the keyboard commands on-screen when it starts. Press `b` to close the preview window, or `x` to exit the program. 30 | 31 | To make a new directory for experiments, and make a shortcut, use the command prompt and type: 32 | ```bash 33 | mkdir cambridge_100x_plan_ac127 34 | ln -s cambridge_100x_plan_ac127/ ce 35 | ``` 36 | This will create a directory called ``cambridge_100x_plan_ac127`` and create a "symbolic link" (a sort of shortcut) called ``ce``. This saves a lot of typing in later commands. 37 | 38 | First, find the centre of the USAF pattern using ``microscope_control.py`` as described above: 39 | ```bash 40 | python microscope_control.py 41 | ``` 42 | Press "v" to enable the video feed, and probably press "f" a couple of times to increase step size. Use the arrow keys or WASD to move around, and Q/E to focus. Once you have a sharp image of the centre of the USAF target (i.e. the smallest group), you can press "j" to save a JPEG image. NB images you save using this program may be half-quality depending on the version, and they are stored in Desktop/images (you'll need to copy them into the experiment folder manually). You should have something that looks like the image below - don't worry if it's not the right way up, or if it's slightly squint (the analysis program can cope with some amount of tilt). 43 | 44 | ![Example image of the centre of a USAF 1951 resolution target](example_images/example_usaf.jpg) 45 | 46 | Press "x" to quit the interactive program, and save a full-resolution, raw image into the experiment folder with: 47 | ```bash 48 | raspistill -t 0 --raw ce/usaf_image_raw.jpg 49 | ``` 50 | To generate a smaller, jpeg-only version, you can use the [raw data stripping script](https://github.com/rwb27/usaf_analysis/blob/master/strip_raw_data.py) on the raw image, or the command below: 51 | ```bash 52 | raspistill -t 0 ce/usaf_image.jpg 53 | ``` 54 | Optionally, you can save a Z-stack of the USAF target: 55 | ```bash 56 | python acquire_zstack.py ce/usaf_zstack 100 20 57 | ``` 58 | The arguments in the command above are: 59 | 1. The folder where you want to save images (nb it should not exist - you can remove it with rmdir ce/usaf_zstack if the command failed previously) 60 | 2. The number of microsteps to move (100 is appropriate for a 40x objective, 40 or even 20 is appropriate for 100x) 61 | 3. The number of images to acquire 62 | 63 | Next, run ``python microscope_control.py`` again, and centre the vertical edge of a large square in the field of view. You should see something that looks like the image below: 64 | 65 | ![Example image of a vertical edge](example_images/example_v_edge.jpg) 66 | 67 | As before, exit the control script by pressing "x" and run: 68 | ```bash 69 | python measure_distortion.py ce/distortion_v 40 0 40 70 | ``` 71 | Arguments: 72 | 1. Output folder 73 | 2. Shift between images in X (in steps) 74 | 3. Shift between images in Y 75 | 4. Number of images 76 | This will make a folder of images of the edge, moving it horizontally across the field of view. We use this to measure distortion. 77 | 78 | The vertical edge should still be centred. You can now run: 79 | ```bash 80 | python scan_edge.py ce/vertical_edge_zstacks 81 | ``` 82 | Arguments: 83 | 1. Output folder 84 | 2. (optional) shift in X (500 is sensible) 85 | 3. (optional) shift in Y (use 0) 86 | This takes a z stack of images of the edge after autofocusing. If you specify the optional X and Y shifts, it does this three times, once in the centre and once either side. The repeated version is useful because it measures the resolution at the edges of the image, rather than just in the centre. 87 | 88 | Using ``python microscope_control.py`` as before, centre a horizontal edge in the field of view, so you have an image like the one below: 89 | 90 | ![Example image of a horizontal edge](example_images/example_h_edge.jpg) 91 | 92 | Now, repeat the above tests for the horizontal edge: 93 | ```bash 94 | python measure_distortion.py ce/distortion_h 0 40 30 95 | python scan_edge.py ce/horizontal_edge_zstacks 96 | ``` 97 | 98 | You should now have four folders of edge images, plus the USAF target images, plus (optionally) a Z-stack series of USAF images. This is everything you need to run the [analysis scripts](https://github.com/rwb27/usaf_analysis/) on, and characterise the microscope. Copy those files and folders off the Pi (using a USB stick or WinSCP) for analysis later. To shut down the pi, type: 99 | ```bash 100 | sudo shutdown -h now 101 | ``` 102 | -------------------------------------------------------------------------------- /openflexure_microscope/utilities/recalibrate.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | from .. import microscope 3 | import picamera.array 4 | import picamera 5 | import numpy as np 6 | import sys 7 | import time 8 | import matplotlib.pyplot as plt 9 | 10 | def lens_shading_correction_from_rgb(rgb_array, binsize=64): 11 | """Calculate a correction to a lens shading table from an RGB image. 12 | 13 | Returns: 14 | a floating-point table of gains that should multiply the current 15 | lens shading table. 16 | """ 17 | full_resolution = rgb_array.shape[:2] 18 | table_resolution = [(r // binsize) + 1 for r in full_resolution] 19 | lens_shading = np.zeros([4] + table_resolution, dtype=np.float) 20 | 21 | for i in range(3): 22 | # We simplify life by dealing with only one channel at a time. 23 | image_channel = rgb_array[:,:,i] 24 | iw, ih = image_channel.shape 25 | ls_channel = lens_shading[int(i*1.6),:,:] # NB there are *two* green channels 26 | lw, lh = ls_channel.shape 27 | # The lens shading table is rounded **up** in size to 1/64th of the size of 28 | # the image. Rather than handle edge images separately, I'm just going to 29 | # pad the image by copying edge pixels, so that it is exactly 32 times the 30 | # size of the lens shading table (NB 32 not 64 because each channel is only 31 | # half the size of the full image - remember the Bayer pattern... This 32 | # should give results very close to 6by9's solution, albeit considerably 33 | # less computationally efficient! 34 | padded_image_channel = np.pad(image_channel, 35 | [(0, lw*binsize - iw), (0, lh*binsize - ih)], 36 | mode="edge") # Pad image to the right and bottom 37 | assert padded_image_channel.shape == (lw*binsize, lh*binsize), "padding problem" 38 | # Next, fill the shading table (except edge pixels). Please excuse the 39 | # for loop - I know it's not fast but this code needn't be! 40 | box = 3 # We average together a square of this side length for each pixel. 41 | # NB this isn't quite what 6by9's program does - it averages 3 pixels 42 | # horizontally, but not vertically. 43 | for dx in np.arange(box) - box//2: 44 | for dy in np.arange(box) - box//2: 45 | ls_channel[:,:] += padded_image_channel[binsize//2+dx::binsize,binsize//2+dy::binsize] 46 | ls_channel /= box**2 47 | # Everything is normalised relative to the centre value. I follow 6by9's 48 | # example and average the central 64 pixels in each channel. 49 | channel_centre = np.mean(image_channel[iw//2-4:iw//2+4, ih//2-4:ih//2+4]) 50 | ls_channel /= channel_centre 51 | print("channel {} centre brightness {}".format(i, channel_centre)) 52 | # NB the central pixel should now be *approximately* 1.0 (may not be exactly 53 | # due to different averaging widths between the normalisation & shading table) 54 | # For most sensible lenses I'd expect that 1.0 is the maximum value. 55 | # NB ls_channel should be a "view" of the whole lens shading array, so we don't 56 | # need to update the big array here. 57 | print("min {}, max {}".format(ls_channel.min(), ls_channel.max())) 58 | # What we actually want to calculate is the gains needed to compensate for the 59 | # lens shading - that's 1/lens_shading_table_float as we currently have it. 60 | lens_shading[2,...] = lens_shading[1,...] # Duplicate the green channels 61 | gains = 1.0/lens_shading # 32 is unity gain 62 | return gains 63 | 64 | def gains_to_lst(gains): 65 | """Given a lens shading gains table (where no gain=1.0), convert to 8-bit.""" 66 | lst = gains / np.min(gains)*32 # minimum gain is 32 (= unity gain) 67 | lst[lst > 255] = 255 # clip at 255 68 | return lst.astype(np.uint8) 69 | 70 | def generate_lens_shading_table_closed_loop(output_fname="microscope_settings.npz", 71 | n_iterations=5, 72 | images_to_average=5): 73 | """Reset the camera's parameters, and recalibrate the lens shading to get unifrom images. 74 | 75 | This function requires the microscope to be set up with a blank, uniformly 76 | illuminated field of view. When it runs, it first auto-exposes, then fixes 77 | the gains/shutter speed and resets the lens shading correction to a unity 78 | gain. Rather than take a single raw image and calibrate from that (as 79 | done in the open loop version, which is a more or less direct Python port 80 | of 6by9's C code), we do it incrementally. Each iteration (of a default 5) 81 | consists of acquiring a processed RGB image, then adjusting the lens shading 82 | table to make it uniform. It seems that doing this 3-5 times gives much 83 | better results than just doing it once. 84 | 85 | At the end, all camera settings are saved into the output file, where they 86 | can be used to set up a microscope with `load_microscope`. 87 | """ 88 | print("Regenerating the camera settings, including lens shading.") 89 | print("This will only work if the camera is looking at something uniform and white.") 90 | # Start by loading the raw image from the Pi camera. This creates a ``picamera.PiBayerArray``. 91 | with picamera.PiCamera() as cam: 92 | lens_shading_table = np.zeros(cam._lens_shading_table_shape(), dtype=np.uint8) + 32 93 | gains = np.ones_like(lens_shading_table, dtype=np.float) 94 | max_res = cam.MAX_RESOLUTION 95 | # Open the microscope and start with flat (i.e. no) lens shading correction. 96 | with microscope.load_microscope(lens_shading_table=lens_shading_table, 97 | resolution=max_res) as ms: 98 | ms.camera.start_preview(resolution=(1080*4/3, 1080)) 99 | def get_rgb_image(): # shorthand for taking an RGB image 100 | return ms.rgb_image(use_video_port=True, resize=(max_res[0]//2, max_res[1]//2)) 101 | ms.freeze_camera_settings(wait_before=4) 102 | # Adjust the shutter speed until the brightest pixels are giving a set value (say 220) 103 | for i in range(3): 104 | ms.camera.shutter_speed = int(ms.camera.shutter_speed * 150.0 / np.max(get_rgb_image())) 105 | time.sleep(1) 106 | 107 | #ms.camera.shutter_speed /=2 108 | for i in range(n_iterations): 109 | print("Optimising lens shading, pass {}/{}".format(i+1, n_iterations)) 110 | # Take an RGB (i.e. processed) image, and calculate the change needed in the shading table 111 | images = [] #averaging to reduce noise 112 | for j in range(images_to_average): 113 | images.append(get_rgb_image()) 114 | rgb_image = np.mean(images, axis=0, dtype=np.float) 115 | incremental_gains = lens_shading_correction_from_rgb(rgb_image, 64//2) 116 | gains *= incremental_gains#**0.8 117 | # Apply this change (actually apply a bit less than the change) 118 | ms.camera.lens_shading_table = gains_to_lst(gains*32) 119 | time.sleep(2) 120 | 121 | # Fix the AWB gains so the image is neutral 122 | channel_means = np.mean(np.mean(get_rgb_image(), axis=0, dtype=np.float), axis=0) 123 | old_gains = ms.camera.awb_gains 124 | ms.camera.awb_gains = (channel_means[1]/channel_means[0] * old_gains[0], channel_means[1]/channel_means[2]*old_gains[1]) 125 | time.sleep(1) 126 | 127 | # Adjust shutter speed to make the image bright but not saturated 128 | for i in range(3): 129 | ms.camera.shutter_speed = int(ms.camera.shutter_speed * 230.0 / np.max(get_rgb_image())) 130 | time.sleep(1) 131 | 132 | settings = ms.settings_dict() 133 | settings['lens_shading_table'] = ms.camera.lens_shading_table 134 | time.sleep(1) 135 | 136 | for k in settings: 137 | print("{}: {}".format(k, settings[k])) 138 | np.savez(output_fname, **settings) 139 | print("Lens shading table written to {}".format(output_fname)) 140 | 141 | if __name__ == '__main__': 142 | try: 143 | generate_lens_shading_table_closed_loop(sys.argv[1]) 144 | except: 145 | generate_lens_shading_table_closed_loop() 146 | -------------------------------------------------------------------------------- /openflexure_microscope/keyboard_control.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | #!/usr/bin/env python 3 | """ 4 | Simple keyboard-based controller for the OpenFlexure Microscope. 5 | 6 | Written 2016 by Richard Bowman, Abhishek Ambekar, James Sharkey and Darryl Foo 7 | Substantially rewritten 2018 by Richard Bowman 8 | 9 | Released under GNU GPL v3 or later. 10 | 11 | Usage: 12 | python -m openflexure_microscope 13 | 14 | Options: 15 | --output= Set output directory/filename [default: ~/Desktop/images] 16 | -h --help Show this screen. 17 | """ 18 | from __future__ import print_function 19 | import io 20 | import sys 21 | import os 22 | import time 23 | import argparse 24 | import numpy as np 25 | import picamera 26 | from builtins import input 27 | from readchar import readchar, readkey 28 | from openflexure_stage import OpenFlexureStage 29 | from .microscope import load_microscope 30 | 31 | def validate_filepath(filepath): 32 | """Check the filepath is valid, creating dirs if needed 33 | The final format is ~/Desktop/images/image_%d.img 34 | %d is formatted with number by (filepath %n) 35 | https://pyformat.info/""" 36 | 37 | filepath = os.path.expanduser(filepath) 38 | if "%d" not in filepath and ".jp" not in filepath: 39 | if not os.path.isdir(filepath): 40 | os.mkdir(filepath) 41 | return os.path.join(filepath, "image_%03d.jpg") 42 | 43 | elif "%d" not in filepath and ".jp" in filepath: 44 | 'add automatic numbering to filename' 45 | filepath = filepath.split('.') 46 | filepath = filepath[0] + '_%03d.' + filepath[1] 47 | return filepath 48 | 49 | elif "%d" in filepath and ".jp" in filepath: 50 | return filepath 51 | 52 | else: 53 | raise ValueError("Error setting output filepath. Valid filepaths should" 54 | " either be [creatable] directories, or end with a " 55 | "filename that contains '%d' and ends in '.jpg' or '.jpeg'") 56 | 57 | def parse_command_line_arguments(): 58 | """Parse command line arguments""" 59 | parser = argparse.ArgumentParser(description="Control the microscope using keyboard commands") 60 | parser.add_argument("--output", help="directory or filepath (with %d wildcard) for saved images", default="~/Desktop/images") 61 | args = parser.parse_args() 62 | return args 63 | 64 | class InteractiveParameter(object): 65 | """This class is intended to allow a setting to be easily controlled. 66 | 67 | The basic version allows the value to be picked from a list. 68 | """ 69 | _value = None 70 | name = "" 71 | allowed_values = [] 72 | wrap = False 73 | 74 | def __init__(self, name, allowed_values, wrap=False, initial_value=None, readonly=False): 75 | """Create an object to manage a parameter. 76 | 77 | name: the name of the setting 78 | allowed_values: a list of values which are permitted 79 | wrap: whether incrementing past the end wraps to the start. 80 | """ 81 | self.name = name 82 | self.allowed_values = allowed_values 83 | self.wrap = wrap 84 | self.readonly = readonly 85 | if initial_value is None: 86 | self._value = allowed_values[0] 87 | else: 88 | self._value = initial_value 89 | 90 | @property 91 | def value(self): 92 | """The value of the property we're manipulating""" 93 | return self._value 94 | @value.setter 95 | def value(self, newvalue): 96 | if not self.readonly: 97 | self._value = newvalue 98 | else: 99 | print("Warning: {} is a read-only property.".format(self.name)) 100 | 101 | def current_index(self): 102 | """The index (in the allowed_values list) of the current value.""" 103 | try: 104 | return list(self.allowed_values).index(self.value) 105 | except ValueError: 106 | try: 107 | allowed = np.array(self.allowed_values) 108 | return np.argmin((allowed - float(self.value))**2) 109 | except: 110 | print("Warning: the value of {} was {}, which is neither " 111 | "allowed nor numerical!".format(self.name, self.value)) 112 | return 0 113 | 114 | def change(self, step): 115 | """Change the value of this property by +/- 1 step""" 116 | assert step in [-1, 1], "Step must be in [-1, 1]" 117 | if self.readonly: 118 | return #don't change the property if we can't change it! 119 | i = self.current_index() + step 120 | N = len(self.allowed_values) 121 | if self.wrap: 122 | i = (i + N) % N # this ensures we wrap if i would be invalid 123 | if i >= 0 and i < N: 124 | self.value = self.allowed_values[i] 125 | 126 | class FunctionParameter(InteractiveParameter): 127 | def __init__(self, name, function, args=[], kwargs={}): 128 | """Create a 'parameter' to run a function. 129 | 130 | name: the name of the function 131 | function: the callable to run 132 | args, kwargs: arguments for the above 133 | """ 134 | self.name = name 135 | self.function = function 136 | self.f_args = args 137 | self.f_kwargs = kwargs 138 | 139 | @property 140 | def value(self): 141 | return "press +" 142 | @value.setter 143 | def value(self): 144 | print("Cannot set the value of a function parameter") 145 | 146 | def current_index(self): 147 | return 0 148 | 149 | def change(self, step): 150 | self.function(*self.f_args, **self.f_kwargs) 151 | 152 | 153 | class InteractiveCameraParameter(InteractiveParameter): 154 | """An InteractiveParameter to control a camera property.""" 155 | def __init__(self, camera, name, allowed_values, getter_conversion=lambda x: x, setter_conversion=lambda x: x, **kwargs): 156 | """See InteractiveParameter for details - first arg is a PiCamera.""" 157 | self._camera = camera 158 | self.getter_conversion = getter_conversion 159 | self.setter_conversion = setter_conversion 160 | InteractiveParameter.__init__(self, name, allowed_values, **kwargs) 161 | 162 | @property 163 | def value(self): 164 | return self.getter_conversion(getattr(self._camera, self.name)) 165 | @value.setter 166 | def value(self, newvalue): 167 | if not self.readonly: 168 | try: 169 | setattr(self._camera, self.name, self.setter_conversion(newvalue)) 170 | time.sleep(0.3) # We wait so that, when we read back the value, it has updated. 171 | # the 0.3s time constant was determined by trial and error... 172 | except: 173 | print("Error setting camera.{} to {}. Perhaps your version of " 174 | "picamera does not support it?".format(self.name, newvalue)) 175 | else: 176 | print("Warning: {} is a read-only property.".format(self.name)) 177 | 178 | class ReadOnlyObjectParameter(InteractiveParameter): 179 | """A dummy InteractiveParameter that only reads things.""" 180 | def __init__(self, obj, name, filter_function=lambda x: x): 181 | """Create a dummy parameter that reads a value from an object.""" 182 | self.obj = obj 183 | self.filter_function = filter_function 184 | InteractiveParameter.__init__(self, name, [None], readonly=True) 185 | 186 | @property 187 | def value(self): 188 | return self.filter_function(getattr(self.obj, self.name)) 189 | 190 | def current_index(self): 191 | return 0 192 | 193 | def change(self, d): 194 | pass 195 | 196 | def image_stack(ms, raw=False): 197 | """Acquire a stack of images, prompting the operator for parameters""" 198 | ms.camera.stop_preview() 199 | try: 200 | output_dir = os.path.expanduser(input("Output directory: ")) 201 | os.mkdir(output_dir) 202 | step_size = [int(input("{} step size: ".format(ax))) for ax in ['X', 'Y', 'Z']] 203 | n_steps = int(input("Number of images: ")) 204 | ms.camera.start_preview() 205 | ms.camera.annotate_text = "" 206 | ms.acquire_image_stack(step_size, n_steps, output_dir, raw=raw) 207 | ms.camera.annotate_text = "Acquired {} images to {}".format(n_steps, output_dir) 208 | time.sleep(1) 209 | except Exception as e: 210 | print("Error: {}".format(e)) 211 | 212 | 213 | def control_parameters_from_microscope(microscope): 214 | """Create a list of InteractiveParameter objects to control a microscope.""" 215 | cam = microscope.camera 216 | stage = microscope.stage 217 | return [ 218 | InteractiveParameter(None, [None]), # TODO: find a nicer way to hide the parameter display! 219 | InteractiveParameter("step_size", 2**np.arange(14), initial_value=256), 220 | InteractiveCameraParameter(cam, "shutter_speed", 10.0**np.linspace(2,5,28), setter_conversion=int), 221 | InteractiveCameraParameter(cam, "analog_gain", 2**np.linspace(-2,2,9)), 222 | InteractiveCameraParameter(cam, "digital_gain", 2**np.linspace(-2,2,9)), 223 | FunctionParameter("coarse autofocus", microscope.autofocus, [np.linspace(-1280,1280,11)]), 224 | FunctionParameter("medium autofocus", microscope.autofocus, [np.linspace(-320,320,11)]), 225 | FunctionParameter("fine autofocus", microscope.autofocus, [np.linspace(-80,80,11)]), 226 | FunctionParameter("image stack", image_stack, [microscope]), 227 | FunctionParameter("image stack [raw]", image_stack, [microscope], {'raw':True}), 228 | InteractiveCameraParameter(cam, "brightness", np.linspace(0,100,11), setter_conversion=int), 229 | InteractiveCameraParameter(cam, "contrast", np.linspace(-50,50,11), setter_conversion=int), 230 | InteractiveCameraParameter(microscope, "zoom", 2**np.linspace(0,4,9)), 231 | ReadOnlyObjectParameter(cam, "awb_gains", filter_function=lambda a_b: [float(a_b[0]), float(a_b[1])]), 232 | ReadOnlyObjectParameter(stage, "position", filter_function=str), 233 | ] 234 | 235 | def parameter_with_name(name, parameter_list): 236 | """Retrieve a parameter with the given name from a list""" 237 | for p in parameter_list: 238 | if p.name == name: 239 | return p 240 | raise KeyError("No parameter with the requested name was found.") 241 | 242 | def control_microscope_with_keyboard(output="./images", dummy_stage=False, settings_file="microscope_settings.npz"): 243 | filepath = validate_filepath(output) 244 | 245 | with load_microscope(settings_file, dummy_stage=dummy_stage) as ms: 246 | camera = ms.camera 247 | stage = ms.stage 248 | camera.annotate_text_size=50 249 | print("wasd to move in X/Y, qe for Z\n" 250 | "r/f to decrease/increase step size.\n" 251 | "v/b to start/stop video preview.\n" 252 | "i/o to zoom in/out.\n" 253 | "[/] to select camera parameters, and +/- to adjust them\n" 254 | "j to save jpeg file, k to change output path.\n" 255 | "x to quit") 256 | control_parameters = control_parameters_from_microscope(ms) 257 | current_parameter = 0 258 | parameter = control_parameters[current_parameter] 259 | step_param = parameter_with_name("step_size", control_parameters) 260 | zoom_param = parameter_with_name("zoom", control_parameters) 261 | move_keys = {'w': [0,1,0], 262 | 'a': [1,0,0], 263 | 's': [0,-1,0], 264 | 'd': [-1,0,0], 265 | 'q': [0,0,-1], 266 | 'e': [0,0,1]} 267 | while True: 268 | c = readkey() 269 | if c == 'x': #quit 270 | break 271 | elif c in list(move_keys.keys()): 272 | # move the stage with quake-style keys 273 | stage.move_rel( np.array(move_keys[c]) * step_param.value) 274 | elif c in ['r', 'f']: 275 | step_param.change(1 if c=='r' else -1) 276 | elif c in ['i', 'o']: 277 | zoom_param.change(1 if c=='i' else -1) 278 | elif c in ['[', ']', '-', '_', '=', '+']: 279 | if c in ['[', ']']: # scroll through parameters 280 | N = len(control_parameters) 281 | d = 1 if c == ']' else -1 282 | current_parameter = (current_parameter + N + d) % N 283 | parameter = control_parameters[current_parameter] 284 | elif c in ['+', '=']: # change the current parameter 285 | parameter.change(1) 286 | else: #c in ['-', ['_']: 287 | parameter.change(-1) 288 | message = "{}: {}".format(parameter.name, parameter.value) 289 | if parameter.name is not None: 290 | print(message) 291 | camera.annotate_text = message 292 | else: 293 | camera.annotate_text = "" 294 | elif c == "v": 295 | #camera.start_preview(resolution=(1080*4//3,1080)) 296 | camera.start_preview(resolution=(480*4//3,480)) 297 | elif c == "b": 298 | camera.stop_preview() 299 | elif c == "j": 300 | n = 0 301 | while os.path.isfile(os.path.join(filepath % n)): 302 | n += 1 303 | camera.capture(filepath % n, format="jpeg", bayer=True) 304 | camera.annotate_text="Saved '%s'" % (filepath % n) 305 | time.sleep(0.5) 306 | camera.annotate_text="" 307 | elif c == "k": 308 | camera.stop_preview() 309 | new_filepath = input("The new output location can be a directory or \n" 310 | "a filepath. Directories will be created if they \n" 311 | "don't exist, filenames must contain '%d' and '.jp'.\n" 312 | "New filepath: ") 313 | if len(new_filepath) > 3: 314 | filepath = validate_filepath(new_filepath) 315 | print("New output filepath: %s\n" % filepath) 316 | 317 | 318 | 319 | 320 | if __name__ == '__main__': 321 | args = parse_command_line_arguments() 322 | control_microscope_with_keyboard(**args) 323 | 324 | -------------------------------------------------------------------------------- /openflexure_microscope/microscope.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | import picamera 3 | from picamera import PiCamera 4 | import picamera.array 5 | import numpy as np 6 | import scipy 7 | from scipy import ndimage 8 | import time 9 | import matplotlib.pyplot as plt 10 | from openflexure_stage import OpenFlexureStage 11 | from contextlib import contextmanager, closing 12 | import os 13 | 14 | picam2_full_res = (3280, 2464) 15 | picam2_half_res = tuple([d/2 for d in picam2_full_res]) 16 | picam2_quarter_res = tuple([d/4 for d in picam2_full_res]) 17 | # The dicts below determine the settings that are loaded from, and saved to, 18 | # the npz settings file. See extract_settings and load_microscope for details. 19 | picamera_init_settings = {"lens_shading_table": None, "resolution": tuple} 20 | picamera_later_settings = {"awb_mode":str, 21 | "awb_gains":tuple, 22 | "shutter_speed":"[()]", 23 | "analog_gain":"[()]", 24 | "digital_gain":"[()]", 25 | "brightness":"[()]", 26 | "contrast":"[()]", 27 | } 28 | 29 | def picamera_supports_lens_shading(): 30 | """Determine whether the picamera module supports lens shading. 31 | 32 | As of March 2018, picamera did not wrap the necessary MMAL commands to 33 | set the lens shading table, or to write the value of analog or digital 34 | gain. I have a forked version of the library that does support these. 35 | 36 | For ease of use by people who don't want those features, this library 37 | does not have a hard dependency on lens shading. However, we need to 38 | check in some places whether it's available. 39 | """ 40 | return hasattr(PiCamera, "lens_shading_table") 41 | 42 | # For backwards compatibility, remove settings that aren't available 43 | if not picamera_supports_lens_shading(): 44 | # remove settings from the dictionaries that aren't available 45 | del picamera_init_settings['lens_shading_table'] 46 | del picamera_later_settings['analog_gain'] 47 | del picamera_later_settings['digital_gain'] 48 | print("WARNING: the currently-installed picamera library does not support all " 49 | "the features of the openflexure microscope software. These features " 50 | "include lens shading control and setting the analog/digital gain.\n" 51 | "\n" 52 | "See the installation instructions for how to fix this:\n" 53 | "https://github.com/rwb27/openflexure_microscope_software") 54 | 55 | def round_resolution(res): 56 | """Round up the camera resolution to units of 32 and 16 in x and y""" 57 | return tuple([int(q*np.ceil(res[i]/float(q))) for i, q in enumerate([32,16])]) 58 | 59 | def decimate_to(shape, image): 60 | """Decimate an image to reduce its size if it's too big.""" 61 | decimation = np.max(np.ceil(np.array(image.shape, dtype=np.float)[:len(shape)]/np.array(shape))) 62 | return image[::int(decimation), ::int(decimation), ...] 63 | 64 | def sharpness_sum_lap2(rgb_image): 65 | """Return an image sharpness metric: sum(laplacian(image)**")""" 66 | image_bw=np.mean(decimate_to((1000,1000), rgb_image),2) 67 | image_lap=ndimage.filters.laplace(image_bw) 68 | return np.mean(image_lap.astype(np.float)**4) 69 | 70 | def sharpness_edge(image): 71 | """Return a sharpness metric optimised for vertical lines""" 72 | gray = np.mean(image.astype(float), 2) 73 | n = 20 74 | edge = np.array([[-1]*n + [1]*n]) 75 | return np.sum([np.sum(ndimage.filters.convolve(gray,W)**2) 76 | for W in [edge, edge.T]]) 77 | @contextmanager 78 | def set_properties(obj, **kwargs): 79 | """A context manager to set, then reset, certain properties of an object. 80 | 81 | The first argument is the object, subsequent keyword arguments are properties 82 | of said object, which are set initially, then reset to their previous values. 83 | """ 84 | saved_properties = {} 85 | for k in kwargs.keys(): 86 | try: 87 | saved_properties[k] = getattr(obj, k) 88 | except AttributeError: 89 | print("Warning: could not get {} on {}. This property will not be restored!".format(k, obj)) 90 | for k, v in kwargs.items(): 91 | setattr(obj, k, v) 92 | try: 93 | yield 94 | finally: 95 | for k, v in saved_properties.items(): 96 | setattr(obj, k, v) 97 | 98 | 99 | class Microscope(object): 100 | def __init__(self, camera=None, stage=None): 101 | """Create the microscope object. The camera and stage should already be initialised.""" 102 | self.camera = camera 103 | self.stage = stage 104 | self.stage.backlash = np.zeros(3, dtype=np.int) 105 | 106 | def close(self): 107 | """Shut down the microscope hardware.""" 108 | self.camera.close() 109 | self.stage.close() 110 | 111 | def rgb_image_old(self, use_video_port=True): 112 | """Capture a frame from a camera and output to a numpy array""" 113 | res = round_resolution(self.camera.resolution) 114 | shape = (res[1], res[0], 3) 115 | buf = np.empty(np.product(shape), dtype=np.uint8) 116 | self.camera.capture(buf, 117 | format='rgb', 118 | use_video_port=use_video_port) 119 | #get an image, see picamera.readthedocs.org/en/latest/recipes2.html 120 | return buf.reshape(shape) 121 | 122 | def rgb_image(self, use_video_port=True, resize=None): 123 | """Capture a frame from a camera and output to a numpy array""" 124 | with picamera.array.PiRGBArray(self.camera, size=resize) as output: 125 | self.camera.capture(output, 126 | format='rgb', 127 | resize=resize, 128 | use_video_port=use_video_port) 129 | #get an image, see picamera.readthedocs.org/en/latest/recipes2.html 130 | return output.array 131 | 132 | def freeze_camera_settings(self, iso=None, wait_before=2, wait_after=0.5): 133 | """Turn off as much auto stuff as possible (except lens shading) 134 | 135 | NB if the camera was created with load_microscope, this is not necessary. 136 | """ 137 | if iso is not None: 138 | self.camera.iso = iso 139 | time.sleep(wait_before) 140 | self.camera.shutter_speed = self.camera.exposure_speed 141 | self.camera.exposure_mode = "off" 142 | g = self.camera.awb_gains 143 | self.camera.awb_mode = "off" 144 | self.camera.awb_gains = g 145 | print("Camera settings are frozen. Analogue gain: {}, Digital gain: {}, Exposure speed: {}, AWB gains: {}".format(self.camera.analog_gain, self.camera.digital_gain, self.camera.exposure_speed, self.camera.awb_gains)) 146 | time.sleep(wait_after) 147 | 148 | def autofocus(self, dz, settle=0.5, metric_fn=sharpness_sum_lap2): 149 | """Perform a simple autofocus routine. 150 | 151 | The stage is moved to z positions (relative to current position) in dz, 152 | and at each position an image is captured and the sharpness function 153 | evaulated. We then move back to the position where the sharpness was 154 | highest. No interpolation is performed. 155 | 156 | dz is assumed to be in ascending order (starting at -ve values) 157 | """ 158 | with set_properties(self.stage, backlash=256): 159 | sharpnesses = [] 160 | positions = [] 161 | self.camera.annotate_text = "" 162 | for i in self.stage.scan_z(dz, return_to_start=False): 163 | positions.append(self.stage.position[2]) 164 | time.sleep(settle) 165 | sharpnesses.append(metric_fn(self.rgb_image( 166 | use_video_port=True, 167 | resize=(640,480)))) 168 | newposition = positions[np.argmax(sharpnesses)] 169 | self.stage.focus_rel(newposition - self.stage.position[2]) 170 | return positions, sharpnesses 171 | 172 | def acquire_image_stack(self, step_displacement, n_steps, output_dir, raw=False): 173 | """Scan an edge across the field of view, to measure distortion. 174 | 175 | You should start this routine with the edge positioned in the centre of the 176 | microscope's field of view. You specify the x,y,z shift between images, and 177 | the number of images - these points will be distributed either side of where 178 | you start. 179 | 180 | step_displacement: a 3-element array/list specifying the step (if a scalar 181 | is passed, it's assumed to be Z) 182 | n_steps: the number of steps to take 183 | output_dir: the directory in which to save images 184 | backlash: the backlash correction amount (default: 128 steps) 185 | """ 186 | # Ensure the displacement per step is an array, and that scalars do z steps 187 | step_displacement = np.array(step_displacement) 188 | if len(step_displacement.shape) == 0: 189 | step_displacement = np.array([0, 0, step_displacement.value]) 190 | elif step_displacement.shape == (1,): 191 | step_displacement = np.array([0, 0, step_displacement[0]]) 192 | ii = np.arange(n_steps) - (n_steps - 1.0)/2.0 # an array centred on zero 193 | scan_points = ii[:, np.newaxis] * step_displacement[np.newaxis, :] 194 | 195 | with set_properties(self.stage, backlash=256): 196 | for i in self.stage.scan_linear(scan_points): 197 | time.sleep(1) 198 | filepath = os.path.join(output_dir,"image_%03d_x%d_y%d_z%d.jpg" % 199 | ((i,) + tuple(self.stage.position))) 200 | print("capturing {}".format(filepath)) 201 | self.camera.capture(filepath, use_video_port=False, bayer=raw) 202 | time.sleep(0.5) 203 | 204 | def settings_dict(self): 205 | """Return all the relevant settings as a dictionary.""" 206 | settings = {} 207 | for k in list(picamera_later_settings.keys()) + list(picamera_init_settings.keys()): 208 | settings[k] = getattr(self.camera, k) 209 | return settings 210 | 211 | def save_settings(self, npzfile): 212 | "Save the microscope's current settings to an npz file" 213 | np.savez(npzfile, **self.settings_dict()) 214 | 215 | @property 216 | def zoom(self): 217 | """A scalar property that sets the zoom value of the camera. 218 | 219 | camera.zoom is a 4-element field of view specifying the region of the 220 | sensor that is visible, this is a simple scalar, where 1 means the whole 221 | FoV is returned and >1 means we zoom in (on the current centre of the 222 | FoV, which may or may not be (0.5,0.5) 223 | """ 224 | fov = self.camera.zoom 225 | return 2.0/(fov[2] + fov[3]) 226 | 227 | @zoom.setter 228 | def zoom(self, newvalue): 229 | """Set the zoom of the camera, keeping the current image centre""" 230 | if newvalue < 1.0: 231 | newvalue = 1.0 232 | fov = self.camera.zoom 233 | centre = np.array([fov[0] + fov[2]/2.0, fov[1] + fov[3]/2.0]) 234 | size = 1.0/newvalue 235 | # If the new zoom value would be invalid, move the centre to 236 | # keep it within the camera's sensor (this is only relevant 237 | # when zooming out, if the FoV is not centred on (0.5, 0.5) 238 | for i in range(2): 239 | if np.abs(centre[i] - 0.5) + size/2 > 0.5: 240 | centre[i] = 0.5 + (1.0 - size)/2 * np.sign(centre[i]-0.5) 241 | print("setting zoom, centre {}, size {}".format(centre, size)) 242 | new_fov = (centre[0] - size/2, centre[1] - size/2, size, size) 243 | self.camera.zoom = new_fov 244 | 245 | 246 | def extract_settings(source_dict, converters): 247 | """Extract a subset of a dictionary of settings. 248 | 249 | For each item in ``source_dict`` that shares a key with an item in 250 | ``converters``, return a dictionary of values that have been 251 | processed using the conversion functions in the second dict. 252 | 253 | NB "None" is equivalent to no processing, to save some typing. 254 | There are some special string values for converters: 255 | "[()]" will convert a 0-dimensional numpy array to a scalar 256 | "[0]" will return the first element of a 1D array 257 | If either "[()]" or "[0]" is specified and raises an exception, 258 | then we fall back to no processing. This is good if the values 259 | might be from a numpy ``.npz`` file, or might be specified directly. 260 | """ 261 | settings = {} 262 | for k in source_dict: 263 | if k in converters: 264 | if converters[k] is None: 265 | settings[k] = source_dict[k] 266 | elif converters[k] == "[()]": 267 | try: 268 | settings[k] = source_dict[k][()] 269 | except: 270 | settings[k] = source_dict[k] 271 | elif converters[k] == "[0]": 272 | try: 273 | settings[k] = source_dict[k][0] 274 | except: 275 | settings[k] = settings[k] 276 | else: 277 | settings[k] = converters[k](source_dict[k]) 278 | return settings 279 | 280 | 281 | class DummyStage(): 282 | position = np.array([0,0,0]) 283 | def move(self, *args, **kwargs): 284 | pass 285 | def move_rel(self, *args, **kwargs): 286 | pass 287 | def close(self): 288 | pass 289 | 290 | @contextmanager 291 | def load_microscope(npzfile=None, save_settings=False, dummy_stage=True, **kwargs): 292 | """Create a microscope object with specified settings. (context manager) 293 | 294 | This will read microscope settings from a .npz file, and/or from 295 | keyword arguments. It will then create the microscope object, and 296 | close it at the end of the with statement. Keyword arguments will 297 | override settings specified in the file. 298 | 299 | If save_settings is 300 | True, it will attempt to save the microscope's settings at the end of 301 | the with block, to the same filename. If save_settings_on_exit is set 302 | to a string, it should save instead to that filename. 303 | """ 304 | settings = {} 305 | try: 306 | npz = np.load(npzfile) 307 | for k in npz: 308 | settings[k] = npz[k] 309 | except: 310 | pass 311 | settings.update(kwargs) 312 | 313 | if "stage_port" in settings: 314 | stage_port = settings["stage_port"] 315 | del settings["stage_port"] 316 | else: 317 | stage_port = None 318 | 319 | # Open the hardware connections 320 | with closing(DummyStage() if dummy_stage else OpenFlexureStage(stage_port)) as stage, \ 321 | closing(PiCamera(**extract_settings(settings, picamera_init_settings))) as camera: 322 | ms = Microscope(camera, stage) 323 | for k, v in extract_settings(settings, picamera_later_settings).items(): 324 | setattr(ms.camera, k, v) 325 | yield ms # The contents of the with block from which we're called happen here 326 | if save_settings: 327 | if save_settings is True: 328 | save_settings = npzfile 329 | ms.save_settings(save_settings) 330 | 331 | 332 | if __name__ == "__main__": 333 | with picamera.PiCamera() as camera, \ 334 | OpenFlexureStage("/dev/ttyUSB0") as stage: 335 | # camera.resolution=(640,480) 336 | camera.start_preview() 337 | ms = Microscope(camera, stage) 338 | ms.freeze_camera_settings(iso=100) 339 | camera.shutter_speed = camera.shutter_speed / 4 340 | 341 | backlash=128 342 | 343 | for step,n in [(1000,10),(200,10),(100,10),(50,10)]: 344 | dz = (np.arange(n) - (n-1)/2.0) * step 345 | 346 | pos, sharps = ms.autofocus(dz, backlash=backlash) 347 | 348 | 349 | plt.plot(pos,sharps,'o-') 350 | 351 | plt.xlabel('position (Microsteps)') 352 | plt.ylabel('Sharpness (a.u.)') 353 | time.sleep(2) 354 | 355 | plt.show() 356 | 357 | print("Done :)") 358 | 359 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------