Esempio n. 1
0
def pco_edge_camera_child_process(
        data_buffers,
        buffer_shape,
        input_queue,
        output_queue,
        commands,
        pco_edge_type='4.2'  #Change this if you're using a 5.5
):
    """For use with image_data_pipeline.py

    https://github.com/AndrewGYork/tools/blob/master/image_data_pipeline.py
    Debugged for the 4.2, but might work for the 5.5, with some TLC...
    """
    from image_data_pipeline import info, Q, sleep, clock
    try:
        import pco
    except ImportError:
        info("Failed to import pco.py; go get it from github:")
        info("https://github.com/AndrewGYork/tools/blob/master/pco.py")
        raise
    buffer_size = np.prod(buffer_shape)
    info("Initializing...")
    camera = pco.Edge(pco_edge_type=pco_edge_type, verbose=False)
    camera.apply_settings(trigger='auto_trigger')
    camera.arm(num_buffers=3)
    info("Done initializing")
    preframes = 3
    first_trigger_timeout_seconds = 0
    status = 'Normal'
    while True:
        if commands.poll():
            cmd, args = commands.recv()
            info("Command received: " + cmd)
            if cmd == 'apply_settings':
                result = camera.apply_settings(**args)
                camera.arm(num_buffers=3)
                commands.send(result)
            elif cmd == 'get_setting':
                setting = getattr(camera, args['setting'],
                                  'unrecognized_setting')
                commands.send(setting)
            elif cmd == 'set_buffer_shape':
                buffer_shape = args['shape']
                buffer_size = np.prod(buffer_shape)
                commands.send(buffer_shape)
            elif cmd == 'get_status':
                commands.send(status)
            elif cmd == 'reset_status':
                status = 'Normal'
                commands.send(status)
            elif cmd == 'get_preframes':
                commands.send(preframes)
            elif cmd == 'set_preframes':
                preframes = args['preframes']
                commands.send(preframes)
            elif cmd == 'get_first_trigger_timeout_seconds':
                commands.send(first_trigger_timeout_seconds)
            elif cmd == 'set_first_trigger_timeout_seconds':
                first_trigger_timeout_seconds = args[
                    'first_trigger_timeout_seconds']
                commands.send(first_trigger_timeout_seconds)
            elif cmd == 'force_trigger':
                result = camera._force_trigger()
                commands.send(result)
            else:
                info("Unrecognized command: " + cmd)
                commands.send("unrecognized_command")
                continue
        try:
            permission_slip = input_queue.get_nowait()
        except Q.Empty:
            sleep(0.001)  #Non-deterministic sleep time :(
            continue
        if permission_slip is None:  #This is how we signal "shut down"
            output_queue.put(permission_slip)
            break  #We're done
        else:
            # Fill the data buffer with images from the camera
            time_received = clock()
            process_me = permission_slip['which_buffer']
            ## Trust IDP to request a legal num_slices
            num_slices = permission_slip.get('num_slices', buffer_shape[0])
            info("start buffer %i, acquiring %i frames and %i preframes" %
                 (process_me, num_slices, preframes))
            with data_buffers[process_me].get_lock():
                a = np.frombuffer(data_buffers[process_me].get_obj(),
                                  dtype=np.uint16)[:buffer_size].reshape(
                                      buffer_shape)[:num_slices, :, :]
                try:
                    camera.record_to_memory(num_images=a.shape[0] + preframes,
                                            preframes=preframes,
                                            out=a,
                                            first_trigger_timeout_seconds=(
                                                first_trigger_timeout_seconds))
                except pco.TimeoutError as e:
                    info('TimeoutError: %s' % (e.value))
                    status = 'TimeoutError'
                    #FIXME: we can do better, probably. Keep trying?
                    #Should we zero the remainder of 'a'?
                except pco.DMAError:
                    info('DMAError')
                    status = 'DMAError'
                else:
                    status = 'Normal'
            info("end buffer %i, %06f seconds elapsed" %
                 (process_me, clock() - time_received))
            output_queue.put(permission_slip)
    camera.close()
    return None
Esempio n. 2
0
def DMK_camera_child_process(
    data_buffers,
    buffer_shape,
    input_queue,
    output_queue,
    commands):
    """For use with image_data_pipeline.py

    https://github.com/AndrewGYork/tools/blob/master/image_data_pipeline.py
    Debugged for the DMK 33GP031 camera, but might work for the DMK
    23GP031, with some TLC...
    """
    from image_data_pipeline import info, Q, sleep, clock
    try:
        import theimagingsource
    except ImportError:
        info("Failed to import theimagingsource.py; go get it from github:")
        info("https://github.com/AndrewGYork/tools/blob/master" +
             "/theimagingsource.py")
        raise
    buffer_size = np.prod(buffer_shape)
    info("Initializing...")
    # If you have multiple TIS cameras attached to the same computer, we
    # need to know which one to use. You can save an appropriately named
    # text file containing the serial number of the appropriate camera
    # in the current working directory:
    try:
        serial_number = int(open('tis_camera_serial_number.txt', 'rb').read())
    except FileNotFoundError:
        serial_number = None # This only works if there's only one TIS device
    try:
        camera = theimagingsource.DMK_x3GP031(
            verbose=False, serial_number=serial_number)
    except SerialNumberError:
        info("\n\nThere are multiple TIS cameras to choose from. " +
             "Which one should we use?\n\n" +
             "\n\nSave a file called 'tis_camera_serial_number.txt' " +
             "in the working directory,\ncontaining the serial number.\n\n")
        raise SerialNumberError("Multiple TIS cameras, see text above")
    camera.enable_trigger(True)
    trigger_mode = 'auto_trigger'
    camera.start_live(verbose=False)
    info("Done initializing")
    while True:
        if commands.poll():
            cmd, args = commands.recv()
            info("Command received: " + cmd)
            if cmd == 'apply_settings':
                camera.set_exposure(
                    exposure_seconds=1e-6*args['exposure_time_microseconds'],
                    verbose=False)
                assert args['trigger'] in ('auto_trigger', 'external_trigger')
                trigger_mode = args['trigger']
                # Ignore the requested region of interest, for now.
                commands.send(None)
            elif cmd == 'get_setting':
                if args['setting'] == 'trigger_mode':
                    setting = trigger_mode
                elif args['setting'] == 'exposure_time_microseconds':
                    setting = camera.exposure_microseconds
                elif args['setting'] == 'roi':
                    setting = {'left': 1,
                               'right': camera.width,
                               'top': 1,
                               'bottom': camera.height}
                else:
                    setting = getattr(camera, args['setting'],
                                      'unrecognized_setting')
                commands.send(setting)
            elif cmd == 'set_buffer_shape':
                buffer_shape = args['shape']
                buffer_size = np.prod(buffer_shape)
                commands.send(buffer_shape)
            elif cmd == 'set_preframes':
                assert args['preframes'] == 0
                commands.send(0)
            elif cmd == 'get_preframes':
                commands.send(0)
            else:
                info("Unrecognized command: " + cmd)
                commands.send("unrecognized_command")
                continue
        try:
            permission_slip = input_queue.get_nowait()
        except Q.Empty:
            sleep(0.001) #Non-deterministic sleep time :(
            continue
        if permission_slip is None: #This is how we signal "shut down"
            output_queue.put(permission_slip)
            break #We're done
        else:
            """
            Fill the data buffer with images from the camera
            """
            time_received = clock()
            process_me = permission_slip['which_buffer']
            info("start buffer %i, acquiring %i frames"%(
                process_me, buffer_shape[0]))
            with data_buffers[process_me].get_lock():
                a = np.frombuffer(data_buffers[process_me].get_obj(),
                                  dtype=np.uint16)[:buffer_size
                                                   ].reshape(buffer_shape)
                for i in range(a.shape[0]):
                    if trigger_mode == 'auto_trigger':
                        camera.send_trigger()
                    try:
                        camera.snap(
                            output_array=a[i, :, :],
                            verbose=False,
                            timeout_milliseconds=max(
                                1000,
                                500 + camera.exposure_microseconds * 1e-3))
                    except TimeoutError:
                        info("Snap timed out. Zeroing the buffer.")
                        a[i, :, :].fill(0)
                    except theimagingsource.SnapError:
                        info("Snap failed. Zeroing the buffer.")
                        a[i, :, :].fill(0)
            info("end buffer %i, %06f seconds elapsed"%(
                process_me, clock() - time_received))
            output_queue.put(permission_slip)
    camera.close()
    return None