Esempio n. 1
0
def camConfig(camera, **kwargs):
    camera.RegisterConfiguration(pylon.AcquireContinuousConfiguration(),
                                 pylon.RegistrationMode_ReplaceAll,
                                 pylon.Cleanup_Delete)

    if camera.GetDeviceInfo().GetModelName() == "Emulation":
        camera.Open()
        grabResult = camera.GrabOne(6000)
        if grabResult.GrabSucceeded():
            pt = grabResult.GetPixelType()
            if pylon.IsPacked(pt):
                _, new_pt = grabResult._Unpack10or12BitPacked()
                shape, dtype, pixelformat = grabResult.GetImageFormat(new_pt)
            else:
                shape, dtype, pixelformat = grabResult.GetImageFormat(pt)
                _ = grabResult.GetImageBuffer()
        else:
            raise Exception()

        camera.Close()
        camera.RegisterConfiguration(pylon.SoftwareTriggerConfiguration(),
                                     pylon.RegistrationMode_ReplaceAll,
                                     pylon.Cleanup_Delete)
        camera.Open()
        camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)
        return (shape, dtype)

    camera.Open()
    PixelFormat = camera.PixelFormat.GetValue()

    print("resolution : ",
          f"{camera.Width.GetValue()}X{camera.Height.GetValue()}")
    print("Format : ", PixelFormat)

    grabResult = camera.GrabOne(1000)
    if grabResult.GrabSucceeded():
        pt = grabResult.GetPixelType()
        if pylon.IsPacked(pt):
            _, new_pt = grabResult._Unpack10or12BitPacked()
            shape, dtype, pixelformat = grabResult.GetImageFormat(new_pt)
        else:
            shape, dtype, pixelformat = grabResult.GetImageFormat(pt)
            _ = grabResult.GetImageBuffer()

    else:
        print("grab Failed")
        raise Exception('grab failed')
    camera.Close()
    camera.RegisterConfiguration(pylon.SoftwareTriggerConfiguration(),
                                 pylon.RegistrationMode_ReplaceAll,
                                 pylon.Cleanup_Delete)
    camera.Open()
    camera.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)

    return (shape, dtype)
Esempio n. 2
0
 def create(self):
     try:
         self.cam = pylon.InstantCamera(
             pylon.TlFactory.GetInstance().CreateFirstDevice())
         print("\nDevice: {}".format(
             self.cam.GetDeviceInfo().GetModelName()))
         # Software trigger configuration registering
         self.cam.RegisterConfiguration(
             pylon.SoftwareTriggerConfiguration(),
             # pylon.AcquireContinuousConfiguration(),
             pylon.RegistrationMode_ReplaceAll,
             pylon.Cleanup_Delete)
         # Enabling camera events
         self.cam.GrabCameraEvents = True
     except Exception as e:
         print("\nCamera NOT FOUND!")
         print(e)
         raise
Esempio n. 3
0
    def initialize(self):
        """ Initializes the communication with the camera. Get's the maximum and minimum width. It also forces
        the camera to work on Software Trigger.

        .. warning:: It may be useful to integrate other types of triggers in applications that need to
            synchronize with other hardware.

        """
        logger.debug('Initializing Basler Camera')
        tl_factory = pylon.TlFactory.GetInstance()
        devices = tl_factory.EnumerateDevices()
        if len(devices) == 0:
            raise CameraNotFound('No camera found')

        for device in devices:
            if self.cam_num in device.GetFriendlyName():
                self.camera = pylon.InstantCamera()
                self.camera.Attach(tl_factory.CreateDevice(device))
                self.camera.Open()
                self.friendly_name = device.GetFriendlyName()

        if not self.camera:
            msg = f'{self.cam_num} not found. Please check your config file and cameras connected'
            logger.error(msg)
            raise CameraNotFound(msg)

        logger.info(
            f'Loaded camera {self.camera.GetDeviceInfo().GetModelName()}')

        self.max_width = self.camera.Width.Max
        self.max_height = self.camera.Height.Max
        offsetX = self.camera.OffsetX.Value
        offsetY = self.camera.OffsetY.Value
        width = self.camera.Width.Value
        height = self.camera.Height.Value
        self.X = (offsetX, offsetX + width)
        self.Y = (offsetY, offsetY + height)

        self.camera.RegisterConfiguration(pylon.SoftwareTriggerConfiguration(),
                                          pylon.RegistrationMode_ReplaceAll,
                                          pylon.Cleanup_Delete)
        self.set_acquisition_mode(self.MODE_SINGLE_SHOT)
        self.get_size()
        self.get_exposure()
    def __init__(self, serial_number):

        global pylon
        global genicam
        from pypylon import pylon, genicam

        factory = pylon.TlFactory.GetInstance()
        # Find and connect to camera:
        print("Connecting to camera...")
        sn = pylon.CDeviceInfo()
        sn.SetSerialNumber(str(serial_number))
        self.camera = pylon.InstantCamera(factory.CreateDevice(sn))
        self.camera.Open()
        self.timeout = 1000  # in ms
        self.camera.RegisterConfiguration(pylon.SoftwareTriggerConfiguration(),
                                          pylon.RegistrationMode_ReplaceAll,
                                          pylon.Cleanup_Delete)
        # Keep a nodeMap reference so we don't have to re-create a lot
        self.nodeMap = self.camera.GetNodeMap()
        self._abort_acquisition = False
Esempio n. 5
0
            print(
                f'{i} : {caminfo.GetModelName()}, SN:{caminfo.GetSerialNumber()}'
            )
            camera.Close()
        sys.exit(0)

    try:
        sn = pylon.CDeviceInfo()
        sn.SetSerialNumber(args.serial)
        camera = pylon.InstantCamera(factory.CreateDevice(sn))
        camera.Open()
    except:
        raise

    # set standard default configuration from server
    camera.RegisterConfiguration(pylon.SoftwareTriggerConfiguration(),
                                 pylon.RegistrationMode_ReplaceAll,
                                 pylon.Cleanup_Delete)

    # put frame readout affecting settings here, otherwise just use the default
    # default is full sensor size readout
    offX = 0
    offY = 0
    width = camera.WidthMax()
    height = camera.HeightMax()
    if camera.IsGigE():

        settings_dict = {
            'ExposureTimeAbs': 1000,
            'ExposureMode': 'Timed',
            'ExposureAuto': 'Off',
Esempio n. 6
0
from pypylon import pylon

from imageeventprinter import ImageEventPrinter
from configurationeventprinter import ConfigurationEventPrinter

# The exit code of the sample application.
exitCode = 0

# Create an instant camera object for the camera device found first.
camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())

# Register the standard configuration event handler for enabling software triggering.
# The software trigger configuration handler replaces the default configuration
# as all currently registered configuration handlers are removed by setting the registration mode to RegistrationMode_ReplaceAll.
camera.RegisterConfiguration(pylon.SoftwareTriggerConfiguration(), pylon.RegistrationMode_ReplaceAll,
                             pylon.Cleanup_Delete)

# For demonstration purposes only, add sample configuration event handlers to print out information
# about camera use and image grabbing.
camera.RegisterConfiguration(ConfigurationEventPrinter(), pylon.RegistrationMode_Append, pylon.Cleanup_Delete)
camera.RegisterImageEventHandler(ImageEventPrinter(), pylon.RegistrationMode_Append, pylon.Cleanup_Delete)

# Print the model name of the camera.
print("Using device ", camera.GetDeviceInfo().GetModelName())

# The parameter MaxNumBuffer can be used to control the count of buffers
# allocated for grabbing. The default value of this parameter is 10.
camera.MaxNumBuffer = 15

# Open the camera.
    def test_grab_events(self):
        print("test_grab_event")
        self.assertTrue(True)
        # Create an example event handler. In the present case, we use one single camera handler for handling multiple camera events.
        # The handler prints a message for each received event.
        handler1 = SampleCameraEventHandler()

        # Create another more generic event handler printing out information about the node for which an event callback
        # is fired.
        handler2 = CameraEventPrinter()
        # Only look for cameras supported by Camera_t
        info = pylon.DeviceInfo()
        # info.SetDeviceClass( ## fetch deviceclass from environment ##);
        info.SetDeviceClass("BaslerUsb")

        # Create an instant camera object with the first found camera device matching the specified device class.
        camera = pylon.InstantCamera(
            pylon.TlFactory.GetInstance().CreateFirstDevice(info))

        # Register the standard configuration event handler for enabling software triggering.
        # The software trigger configuration handler replaces the default configuration
        # as all currently registered configuration handlers are removed by setting the registration mode to RegistrationMode_ReplaceAll.
        camera.RegisterConfiguration(pylon.SoftwareTriggerConfiguration(),
                                     pylon.RegistrationMode_ReplaceAll,
                                     pylon.Cleanup_Delete)

        # For demonstration purposes only, add sample configuration event handlers to print out information
        # about camera use and image grabbing.
        # camera.RegisterConfiguration(ConfigurationEventPrinter(), pylon.RegistrationMode_Append,
        #                            pylon.Cleanup_Delete)  # Camera use.

        # For demonstration purposes only, register another image event handler.
        camera.RegisterImageEventHandler(SampleImageEventHandler(),
                                         pylon.RegistrationMode_Append,
                                         pylon.Cleanup_Delete)

        # Camera event processing must be activated first, the default is off.
        camera.GrabCameraEvents = True

        # Register an event handler for the Exposure End event. For each event type, there is a "data" node
        # representing the event. The actual data that is carried by the event is held by child nodes of the
        # data node. In the case of the Exposure End event, the child nodes are EventExposureEndFrameID and EventExposureEndTimestamp.
        # The CSampleCameraEventHandler demonstrates how to access the child nodes within
        # a callback that is fired for the parent data node.
        # The user-provided ID eMyExposureEndEvent can be used to distinguish between multiple events (not shown).
        camera.RegisterCameraEventHandler(handler1, "EventExposureEndData",
                                          eMyExposureEndEvent,
                                          pylon.RegistrationMode_ReplaceAll,
                                          pylon.Cleanup_None)

        # The handler is registered for both, the EventExposureEndFrameID and the EventExposureEndTimestamp
        # node. These nodes represent the data carried by the Exposure End event.
        # For each Exposure End event received, the handler will be called twice, once for the frame ID, and
        # once for the time stamp.
        camera.RegisterCameraEventHandler(handler2, "EventExposureEndFrameID",
                                          eMyExposureEndEvent,
                                          pylon.RegistrationMode_Append,
                                          pylon.Cleanup_None)
        camera.RegisterCameraEventHandler(handler2,
                                          "EventExposureEndTimestamp",
                                          eMyExposureEndEvent,
                                          pylon.RegistrationMode_Append,
                                          pylon.Cleanup_None)

        # Open the camera for setting parameters.
        camera.Open()

        camera.ExposureTime.Value = camera.ExposureTime.Min

        # Check if the device supports events.
        if not genicam.IsAvailable(camera.EventSelector):
            raise genicam.RuntimeException(
                "The device doesn't support events.")

        # Enable sending of Exposure End events.
        # Select the event to receive.
        camera.EventSelector = "ExposureEnd"
        # Enable it.
        camera.EventNotification = "On"

        # Start the grabbing of c_countOfImagesToGrab images.
        camera.StartGrabbingMax(self.countOfImagesToGrab)

        # Camera.StopGrabbing() is called automatically by the RetrieveResult() method
        # when c_countOfImagesToGrab images have been retrieved.
        while camera.IsGrabbing():
            # Execute the software trigger. Wait up to 1000 ms for the camera to be ready for trigger.
            if camera.WaitForFrameTriggerReady(
                    100, pylon.TimeoutHandling_ThrowException):
                camera.ExecuteSoftwareTrigger()

            # Retrieve grab results and notify the camera event and image event handlers.
            grabResult = camera.RetrieveResult(100)
            # Nothing to do here with the grab result, the grab results are handled by the registered event handler.

        # Disable sending Exposure End events.
        camera.EventSelector = "ExposureEnd"
        camera.EventNotification = "Off"
        camera.Close()
Esempio n. 8
0
def Test2():

    dirname = "/media/hydrolab/L1/0708/male"
    frame_num = 60000
    try:
        os.mkdir(dirname)
    except FileExistsError as e:
        print("already exists")

    os.environ["PYLON_CAMEMU"] = "2"
    try:
        T1 = pylon.TlFactory.GetInstance()
        lstDevices = T1.EnumerateDevices()
        if len(lstDevices) == 0:
            print("no camera is detected")
        if len(lstDevices) <= 0:
            print(f"ther is no camera")

        camera1 = pylon.InstantCamera(T1.CreateFirstDevice(lstDevices[0]))
        camera2 = pylon.InstantCamera(T1.CreateFirstDevice(lstDevices[1]))

        print("using camera1 : ", camera1.GetDeviceInfo().GetModelName())
        print("using camera2 : ", camera2.GetDeviceInfo().GetModelName())
    except:
        print("init fail")
        exit()

    camera1.RegisterConfiguration(pylon.AcquireContinuousConfiguration(),
                                  pylon.RegistrationMode_ReplaceAll,
                                  pylon.Cleanup_Delete)
    camera2.RegisterConfiguration(pylon.AcquireContinuousConfiguration(),
                                  pylon.RegistrationMode_ReplaceAll,
                                  pylon.Cleanup_Delete)
    camera1.Open()
    camera2.Open()

    re1 = camera1.GrabOne(1000)
    re2 = camera2.GrabOne(1000)
    if re1.GrabSucceeded():
        size1 = re1.GetArray().shape
    else:
        print("C1 grab Failed")
        exit()

    if re2.GrabSucceeded():
        size2 = re2.GetArray().shape

    else:
        print("C2 grab Failed")
        exit()

    camera1.Close()
    camera2.Close()

    camera1.RegisterConfiguration(pylon.SoftwareTriggerConfiguration(),
                                  pylon.RegistrationMode_ReplaceAll,
                                  pylon.Cleanup_Delete)
    camera2.RegisterConfiguration(pylon.SoftwareTriggerConfiguration(),
                                  pylon.RegistrationMode_ReplaceAll,
                                  pylon.Cleanup_Delete)

    camera1.Open()
    camera2.Open()

    camera1.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)
    camera2.StartGrabbing(pylon.GrabStrategy_LatestImageOnly)

    start = time.time()

    for s in tqdm(range(frame_num)):
        camera1.WaitForFrameTriggerReady(200,
                                         pylon.TimeoutHandling_ThrowException)
        camera2.WaitForFrameTriggerReady(200,
                                         pylon.TimeoutHandling_ThrowException)
        camera1.ExecuteSoftwareTrigger()
        camera2.ExecuteSoftwareTrigger()

        re1 = camera1.RetrieveResult(100, pylon.TimeoutHandling_Return)
        re2 = camera2.RetrieveResult(100, pylon.TimeoutHandling_Return)
        np.save(os.path.join(dirname, f"c1_{s}"), re1.GetArray())
        np.save(os.path.join(dirname, f"c2_{s}"), re2.GetArray())

    camera1.Close()
    camera2.Close()

    camera1.RegisterConfiguration(pylon.AcquireContinuousConfiguration(),
                                  pylon.RegistrationMode_ReplaceAll,
                                  pylon.Cleanup_Delete)
    camera2.RegisterConfiguration(pylon.AcquireContinuousConfiguration(),
                                  pylon.RegistrationMode_ReplaceAll,
                                  pylon.Cleanup_Delete)

    camera1.Open()
    camera2.Open()
    camera1.Close()
    camera2.Close()