Skip to main content

ids_peak_afl - A library for auto features

Project description

ids_peak_afl provides python bindings for the IDS peak AFL. It exposes all the functionality of the peak AFL and requires at least the drivers and GenICam transport layers to be installed, which are included in the IDS peak SDK.

Benefit from many Python advantages, for example the interactive programming of your IDS camera. Write and test small code snippets without the complex setup of a programming IDE including a toolchain. This package is ideal for prototyping IDS camera applications for all supported peak AFL platforms (Windows, Linux, Linux Embedded).

Installation

$ pip install ids_peak_afl

Quickstart

This example shows how to open a device, start image acquisition and use the ids_peak_afl package for triggering a host-sided automatic adjustment of image brightness (requires version >=1.2).

NOTE: For the sake of simplicity, most of the error checking has been omitted in this example.

from ids_peak import ids_peak, ids_peak_ipl_extension
from ids_peak_ipl import ids_peak_ipl
from ids_peak_afl import ids_peak_afl


class FinishedCallback(
        ids_peak_afl.FinishedCallback):
    def callback(self) -> None:
        print("ControllerFinishedCallback!")


class ComponentExposureFinishedCallback(
        ids_peak_afl.ComponentExposureFinishedCallback):
    def callback(self) -> None:
        print("ExposureFinishedCallback!")


class ComponentGainFinishedCallback(
        ids_peak_afl.ComponentGainFinishedCallback):
    def callback(self) -> None:
        print("GainFinishedCallback!")


def main():
    # Initialize library calls should be matched by a corresponding
    # Exit or close call
    ids_peak.Library.Initialize()
    ids_peak_afl.Library.Init()

    # Create a DeviceManager object
    device_manager = ids_peak.DeviceManager.Instance()

    try:
        # Update the DeviceManager
        device_manager.Update()

        # Exit program if no device was found
        if device_manager.Devices().empty():
            print("No device found. Exiting Program.")
            return -1

        # Open the first device
        device = device_manager.Devices()[0].OpenDevice(
            ids_peak.DeviceAccessType_Control)

        print(f"Device: {device.SerialNumber()} -> {device.DisplayName()}")

        # Nodemap for accessing GenICam nodes
        remote_nodemap = device.RemoteDevice().NodeMaps()[0]

        # Autofeature manager, which can have multiple controllers
        manager = ids_peak_afl.Manager(remote_nodemap)
        # Create autofocus controller
        controller = manager.CreateController(
            ids_peak_afl.PEAK_AFL_CONTROLLER_TYPE_BRIGHTNESS)

        print(f"Controller Status: {controller.Status()}")
        print(f"Controller Type: {controller.Type()}")

        # Load default camera settings
        remote_nodemap.FindNode("UserSetSelector").SetCurrentEntry("Default")
        remote_nodemap.FindNode("UserSetLoad").Execute()
        remote_nodemap.FindNode("UserSetLoad").WaitUntilDone()

        # Auto brightness mode is split up in two components
        # so you can't use the regular controller.SetMode etc.
        # NOTE: mode is reset to off automatically after the operation finishes
        # when using PEAK_AFL_CONTROLLER_AUTOMODE_ONCE
        controller.BrightnessComponentSetMode(
            ids_peak_afl.PEAK_AFL_CONTROLLER_BRIGHTNESS_COMPONENT_EXPOSURE,
            ids_peak_afl.PEAK_AFL_CONTROLLER_AUTOMODE_ONCE,
        )
        controller.BrightnessComponentSetMode(
            ids_peak_afl.PEAK_AFL_CONTROLLER_BRIGHTNESS_COMPONENT_GAIN,
            ids_peak_afl.PEAK_AFL_CONTROLLER_AUTOMODE_ONCE,
        )

        # Register callbacks
        # NOTE: these have to be assigned, otherwise they get destructed
        # and the callback gets removed
        finished = FinishedCallback(controller)
        exposureFinished = ComponentExposureFinishedCallback(controller)
        gainFinished = ComponentGainFinishedCallback(controller)

        # Open first data stream
        data_stream = device.DataStreams()[0].OpenDataStream()
        # Buffer size
        payload_size = remote_nodemap.FindNode("PayloadSize").Value()

        # Minimum number of required buffers
        buffer_count_max = data_stream.NumBuffersAnnouncedMinRequired()

        # Allocate buffers and add them to the pool
        for buffer_count in range(buffer_count_max):
            # Let the TL allocate the buffers
            buffer = data_stream.AllocAndAnnounceBuffer(payload_size)
            # Put the buffer in the pool
            data_stream.QueueBuffer(buffer)

        # Lock writeable nodes during acquisition
        remote_nodemap.FindNode("TLParamsLocked").SetValue(1)

        print("Starting acquisition...")
        data_stream.StartAcquisition()
        remote_nodemap.FindNode("AcquisitionStart").Execute()
        remote_nodemap.FindNode("AcquisitionStart").WaitUntilDone()

        print("Getting 100 images...")
        # Process 100 images
        for _ in range(100):
            try:
                # Wait for finished/filled buffer event
                buffer = data_stream.WaitForFinishedBuffer(1000)
                img = ids_peak_ipl_extension.BufferToImage(buffer)

                # NOTE: If performance is a concern, then `ids_peak_ipl.ImageConverter`
                #       should be preferred.
                mono_img = img.ConvertTo(ids_peak_ipl.PixelFormatName_Mono8)
                # Put the buffer back in the pool, so it can be filled again
                # NOTE: `ConvertTo` will make a copy, so it is fine to queue
                #       the buffer immediately after.
                data_stream.QueueBuffer(buffer)

                # Process the image in the autofeature manager, which will
                # Apply all the actions of associated controllers
                manager.Process(mono_img)
            except Exception as e:
                print(f"Exception: {e}")

        print("Stopping acquisition...")
        remote_nodemap.FindNode("AcquisitionStop").Execute()
        remote_nodemap.FindNode("AcquisitionStop").WaitUntilDone()

        data_stream.StopAcquisition(ids_peak.AcquisitionStopMode_Default)

        # In case another thread is waiting on WaitForFinishedBuffer
        # you can interrupt it using:
        # data_stream.KillWait()

        # Remove buffers from any associated queue
        data_stream.Flush(ids_peak.DataStreamFlushMode_DiscardAll)

        for buffer in data_stream.AnnouncedBuffers():
            # Remove buffer from the transport layer
            data_stream.RevokeBuffer(buffer)

        # Unlock writeable nodes again
        remote_nodemap.FindNode("TLParamsLocked").SetValue(0)

        # Last auto average for the controller working on a mono image
        print(f"LastAutoAverage: {controller.GetLastAutoAverage()}")

    except Exception as e:
        print(f"EXCEPTION: {e}")
        return -2

    finally:
        ids_peak_afl.Library.Exit()
        ids_peak.Library.Close()


if __name__ == '__main__':
    main()

Documentation

Documentation is available here

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distributions

ids_peak_afl-1.5.0.0-cp37-abi3-win_amd64.whl (642.9 kB view hashes)

Uploaded CPython 3.7+ Windows x86-64

ids_peak_afl-1.5.0.0-cp37-abi3-win32.whl (532.8 kB view hashes)

Uploaded CPython 3.7+ Windows x86

ids_peak_afl-1.5.0.0-cp37-abi3-manylinux_2_24_x86_64.whl (700.7 kB view hashes)

Uploaded CPython 3.7+ manylinux: glibc 2.24+ x86-64

ids_peak_afl-1.5.0.0-cp37-abi3-manylinux_2_24_i686.whl (702.2 kB view hashes)

Uploaded CPython 3.7+ manylinux: glibc 2.24+ i686

ids_peak_afl-1.5.0.0-cp37-abi3-manylinux_2_24_armv7l.whl (631.5 kB view hashes)

Uploaded CPython 3.7+ manylinux: glibc 2.24+ ARMv7l

ids_peak_afl-1.5.0.0-cp37-abi3-manylinux_2_24_aarch64.whl (647.8 kB view hashes)

Uploaded CPython 3.7+ manylinux: glibc 2.24+ ARM64

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page