Exemple #1
0
	def __init__(self,maxCamerasToUse,secperframe):
		try:
			self.spf = secperframe
			# Get the transport layer factory.
			tlFactory = pylon.TlFactory.GetInstance()
		
			# Get all attached devices and exit application if no device is found.
			devices = tlFactory.EnumerateDevices()
			if len(devices) == 0:
				raise pylon.RUNTIME_EXCEPTION("No camera present.")
		
			# Create an array of instant cameras for the found devices and avoid exceeding a maximum number of devices.
			self.cameras = pylon.InstantCameraArray(min(len(devices), maxCamerasToUse))
		
			self.l = self.cameras.GetSize()
			
			self.dimarr=np.zeros((self.l,2),dtype='uint8')
			self.sernum=[None]*self.l
			# Create and attach all Pylon Devices.
			for i, cam in enumerate(self.cameras):
				#Some parameters I'm using now, may change in future.
				cam.Attach(tlFactory.CreateDevice(devices[i]))
				cam.Open()
				cam.AcquisitionFrameRateEnable.SetValue(True)
				cam.AcquisitionFrameRate.SetValue(1/secperframe)
				cam.OffsetX.SetValue(0)
				cam.OffsetY.SetValue(0)
				self.dimarr[i] = [cam.Height.GetMax(),cam.Width.GetMax()]
				self.sernum[i]=cam.GetDeviceInfo().GetSerialNumber()
				cam.ExposureAuto.SetValue('Off')
				cam.GainAuto.SetValue('Off')
				cam.Close()
		except genicam.GenericException as e:
			# Error handling
			print("An exception occurred.", e.GetDescription())		
    def __init__(self, controller: Controller, binning_factor=4, max_cam_count=10, acquisition_timeout=1000, retrieval_timeout=5000, timeout=1):
        super().__init__()
        self._controller = controller
        self._camera_id = f'camera_{uuid.uuid4()}'
        controller.register_sensor(self, self._camera_id)
        self._acquisition_timeout = acquisition_timeout
        self._retrieval_timeout = retrieval_timeout
        self._timeout = timeout

        self._run = False
        self._active = False

        self._tl_factory = pylon.TlFactory.GetInstance()
        devices = self._tl_factory.EnumerateDevices()
        if len(devices) == 0:
            raise pylon.RuntimeException('No cameras attached.')
        self._cameras = pylon.InstantCameraArray(min(len(devices), max_cam_count))

        for i, cam in enumerate(self._cameras):
            cam.Attach(self._tl_factory.CreateDevice(devices[i]))
            # Print the model name of the camera.
            print("Using device ", cam.GetDeviceInfo().GetModelName())

        self._camera.PixelFormat = "RGB8"
        self._camera.BinningHorizontal = binning_factor
        self._camera.BinningVertical = binning_factor
Exemple #3
0
 def disabled_test_grab_multiple_cameras(self):
     twoCamsUsed = False
     # Number of images to be grabbed.
     countOfImagesToGrab = 10
     # Limits the amount of cameras used for grabbing.
     maxCamerasToUse = 2
     # Get the transport layer factory.
     tlFactory = pylon.TlFactory.GetInstance()
     # Get all attached devices and exit application if no device is found.
     devices = tlFactory.EnumerateDevices()
     # Create an array of instant cameras for the found devices and avoid exceeding a maximum number of devices.
     cameras = pylon.InstantCameraArray(min(len(devices), maxCamerasToUse))
     l = cameras.GetSize()
     self.assertEqual(2, l)  # Are 2 Cameras initialized
     # Create and attach all Pylon Devices.
     for i, cam in enumerate(cameras):
         cam.Attach(tlFactory.CreateDevice(devices[i]))
         # Print the model name of the camera.
         print("Using device ", cam.GetDeviceInfo().GetModelName())
     # Starts grabbing for all cameras
     cameras.StartGrabbing()
     # Grab c_countOfImagesToGrab from the cameras.
     for i in range(countOfImagesToGrab):
         if not cameras.IsGrabbing():
             break
         grabResult = cameras.RetrieveResult(
             5000, pylon.TimeoutHandling_ThrowException)
         cameraContextValue = grabResult.GetCameraContext()
         if (cameraContextValue == 1):
             twoCamsUsed = True
         # Now, the image data can be processed.
         self.assertEqual(True, grabResult.GrabSucceeded())
         img = grabResult.GetArray()
         self.assertEqual(0, img[0, 0])
     self.assertTrue(twoCamsUsed)  # Are 2 Cameras actually used
Exemple #4
0
    def reload(self):
        try:
            tlFactory = pylon.TlFactory.GetInstance()
            devices = tlFactory.EnumerateDevices()
            
            self.camera = pylon.InstantCameraArray(min(len(devices), self.maxCamerasToUse))
            l = self.camera.GetSize()

            # Create and attach all Pylon Devices.
            for i, cam in enumerate(self.camera):
                cam.Attach(tlFactory.CreateDevice(devices[i]))
            # Set output pixel format to BGR8 for opencv
            for device in devices:
                
                if 'uc' in device.GetFriendlyName():
                    self.polychromatic_format()
                else:
                    self.monochromatic_format()
                
                


            for i, cam in enumerate(self.camera):
                if(self.camera[i].IsOpen() == False):
                    self.open(i)
            time.sleep(2)

            self.change_config(exposure='standard_exposure',gamma='standard_gamma')           
            self.print_camera_config(key='a')

        except Exception as e:
            logger.debug("CAMERA DEV:" + str(e))
            logger.error("CAMERA DEV Exception:" + str(e))
            traceback.print_exc(file=sys.stdout)
            raise CameraException("Camera basler")
Exemple #5
0
 def get_cameras(self):
     # Get detected cameras
     self.tlFactory = pylon.TlFactory.GetInstance()
     self.devices = self.tlFactory.EnumerateDevices()
     if not self.devices:
         raise ValueError("Could not find any camera")
     else:
         self.cameras = pylon.InstantCameraArray(
             self.camera_config["n_cameras"])
Exemple #6
0
 def test_initialize(self):
     cameraArray = pylon.InstantCameraArray()
     self.assertEqual(0, cameraArray.GetSize())
     cameraArray.Initialize(self.num_dev)
     self.assertEqual(self.num_dev, cameraArray.GetSize())
     v = 0
     for cam in cameraArray:
         v += 1
     self.assertEqual(self.num_dev, v)
Exemple #7
0
 def test_constructor_empty(self):
     cameraArray = pylon.InstantCameraArray()
     self.assertEqual(0, cameraArray.GetSize())
     self.assertFalse(cameraArray.IsGrabbing())
     self.assertFalse(cameraArray.IsOpen())
     self.assertFalse(cameraArray.IsPylonDeviceAttached())
     self.assertFalse(cameraArray.IsCameraDeviceRemoved())
     # Test if no Camera is connected
     for cam in cameraArray:
         self.fail()
Exemple #8
0
    def __init__(self, camsToUse):

        self.tlFactory = pylon.TlFactory.GetInstance()
        maxCamerasToUse = camsToUse

        # Get all attached devices and exit application if no device is found.
        self.devices = self.tlFactory.EnumerateDevices()
        if len(self.devices) == 0:
            raise pylon.RUNTIME_EXCEPTION("No camera present.")

        # Create an array of instant cameras for the found devices and avoid
        # exceeding a maximum number of devices.
        self.cameras = pylon.InstantCameraArray(
            min(len(self.devices), maxCamerasToUse))
Exemple #9
0
  def __init__(self):
    print("init cameras")
    self._tl_factory = pylon.TlFactory.GetInstance()
    self._devices = self._tl_factory.EnumerateDevices()
    self._cameras = pylon.InstantCameraArray(min(len(self._devices), 2))
    print("{0} cameras found".format(len(self._devices)))

    # Create and attach all Pylon Devices.
    for i, cam in enumerate(self._cameras):
      cam.Attach(self._tl_factory.CreateDevice(self._devices[i]))
      self.setup_camera(cam)

      # Print the model name of the camera.
      print("Using device ", cam.GetDeviceInfo().GetSerialNumber())
Exemple #10
0
def attach_cameras(tlFactory, camera_devices, parallel=False):
    try:
        # Create an array of instant cameras for the found devices
        # and avoid exceeding a maximum number of devices.
        cam_array = pylon.InstantCameraArray(
            min(len(camera_devices), maxCamerasToUse))

        for i, camera in enumerate(cam_array):
            # Create an instant camera object
            camera.Attach(tlFactory.CreateDevice(camera_devices[i]))

        print(str(len(camera_devices)) + ' cameras attached.')

    except genicam.GenericException as e:
        print("An exception occurred.")
        print(e.GetDescription())

    return cam_array
Exemple #11
0
    def test_detach_cameras(self):

        cameraArray = pylon.InstantCameraArray(self.num_dev)
        devices = pylon.TlFactory.GetInstance().EnumerateDevices(
            self.device_filter)
        self.assertEqual(len(devices), self.num_dev)
        for i, cam in enumerate(cameraArray):
            self.assertEqual(devices[i].GetDeviceClass(), self.device_class)
            cam.Attach(pylon.TlFactory.GetInstance().CreateDevice(devices[i]))

        cameraArray.Open()
        cameraArray.StartGrabbing()
        cameraArray.DetachDevice()
        self.assertEqual(self.num_dev, cameraArray.GetSize())
        self.assertFalse(cameraArray.IsGrabbing())
        self.assertFalse(cameraArray.IsOpen())
        self.assertFalse(cameraArray.IsPylonDeviceAttached())
        self.assertFalse(cameraArray.IsCameraDeviceRemoved())
    def __init__(self):
        # converting to opencv bgr format (it's needed for displaying the image)
        self.converter = pylon.ImageFormatConverter()
        self.converter.OutputPixelFormat = pylon.PixelType_BGR8packed
        self.converter.OutputBitAlignment = pylon.OutputBitAlignment_MsbAligned

        tlFactory = pylon.TlFactory.GetInstance()
        devices = tlFactory.EnumerateDevices()
        if len(devices) == 0:
            raise pylon.RUNTIME_EXCEPTION("No camera present.")

        cameras = pylon.InstantCameraArray(2)

        for i, camera in enumerate(cameras):
            camera.Attach(tlFactory.CreateDevice(devices[i]))

        self.cameras = cameras
        self.cameras.Open()

        self.script_path = os.path.dirname(os.path.abspath(__file__))
        os.chdir(self.script_path)
Exemple #13
0
    def __init__(self, register_event_listener=False, my_events=None):
        tlFactory = pylon.TlFactory.GetInstance()
        # Get all attached devices and raise an error if no devices found
        devices = tlFactory.EnumerateDevices()
        if not devices:
            raise pylon.RUNTIME_EXCEPTION("No camera present.")

        # Create an array of instant cameras for the found devices and avoid
        # exceeding a maximum number of devices.
        self.cameras = pylon.InstantCameraArray(min(len(devices), MAX_CAMERAS))

        # Create and attach all Pylon Devices.
        for i, cam in enumerate(self.cameras):
            cam.Attach(tlFactory.CreateDevice(devices[i]))
            cam.RegisterConfiguration(my_events, pylon.RegistrationMode_Append,
                                      pylon.Cleanup_Delete)
            # Print the model name of the camera.
            logger.info("Initalizing device : {}".format(
                cam.GetDeviceInfo().GetModelName()))
            if "NIR" in cam.GetDeviceInfo().GetModelName().upper()[-3:]:
                self.nir = self.cameras[i]
            else:
                self.rgb = self.cameras[i]
Exemple #14
0
    def test_connect_cameras(self):
        devices = pylon.TlFactory.GetInstance().EnumerateDevices(
            self.device_filter)
        self.assertEqual(len(devices), self.num_dev)
        cameraArray = pylon.InstantCameraArray(self.num_dev)
        for i, cam in enumerate(cameraArray):
            self.assertEqual(devices[i].GetDeviceClass(), self.device_class)
            cam.Attach(pylon.TlFactory.GetInstance().CreateDevice(devices[i]))

        self.assertEqual(self.num_dev, cameraArray.GetSize())
        self.assertFalse(cameraArray.IsGrabbing())
        self.assertFalse(cameraArray.IsOpen())
        self.assertTrue(cameraArray.IsPylonDeviceAttached())
        self.assertFalse(cameraArray.IsCameraDeviceRemoved())

        cameraArray.Open()

        self.assertEqual(self.num_dev, cameraArray.GetSize())
        self.assertFalse(cameraArray.IsGrabbing())
        self.assertTrue(cameraArray.IsOpen())
        self.assertTrue(cameraArray.IsPylonDeviceAttached())
        self.assertFalse(cameraArray.IsCameraDeviceRemoved())

        cameraArray.StartGrabbing()

        self.assertEqual(self.num_dev, cameraArray.GetSize())
        self.assertTrue(cameraArray.IsGrabbing())
        self.assertTrue(cameraArray.IsOpen())
        self.assertTrue(cameraArray.IsPylonDeviceAttached())
        self.assertFalse(cameraArray.IsCameraDeviceRemoved())

        cameraArray.RetrieveResult(300)

        self.assertEqual(self.num_dev, cameraArray.GetSize())
        self.assertTrue(cameraArray.IsGrabbing())
        self.assertTrue(cameraArray.IsOpen())
        self.assertTrue(cameraArray.IsPylonDeviceAttached())
        self.assertFalse(cameraArray.IsCameraDeviceRemoved())

        cameraArray.StopGrabbing()

        self.assertEqual(self.num_dev, cameraArray.GetSize())
        self.assertFalse(cameraArray.IsGrabbing())
        self.assertTrue(cameraArray.IsOpen())
        self.assertTrue(cameraArray.IsPylonDeviceAttached())
        self.assertFalse(cameraArray.IsCameraDeviceRemoved())

        cameraArray.Close()

        self.assertEqual(self.num_dev, cameraArray.GetSize())
        self.assertFalse(cameraArray.IsGrabbing())
        self.assertFalse(cameraArray.IsOpen())
        self.assertTrue(cameraArray.IsPylonDeviceAttached())
        self.assertFalse(cameraArray.IsCameraDeviceRemoved())

        cameraArray.DestroyDevice()

        self.assertEqual(self.num_dev, cameraArray.GetSize())
        self.assertFalse(cameraArray.IsGrabbing())
        self.assertFalse(cameraArray.IsOpen())
        self.assertFalse(cameraArray.IsPylonDeviceAttached())
        self.assertFalse(cameraArray.IsCameraDeviceRemoved())
    # for demo purposes, we will only look for certain types of cameras
    filters = list()
    filter1 = pylon.DeviceInfo()
    filter1.SetDeviceClass("BaslerUsb")
    filters.append(filter1)

    # detect and enumerate devices into a device info list
    tlFactory = pylon.TlFactory.GetInstance()
    devices = tlFactory.EnumerateDevices(filters)

    # We will use however many cameras are found
    numberOfCameras = len(devices)

    # The InstantCameraArray is generic (interface agnostic)
    # It encapsulates the physical camera and driver into one convinient object
    cameras = pylon.InstantCameraArray(numberOfCameras)

    # Attach each camera in the array to a physical device
    for i in range(cameras.GetSize()):
        cameras[i].Attach(tlFactory.CreateDevice(devices[i]))
        cameras[i].SetCameraContext(i)
        print "Using Camera ", cameras[i].GetCameraContext(
        ), " : ", cameras[i].GetDeviceInfo().GetFriendlyName()

    # Open the cameras to access features
    cameras.Open()

    # We use the Genicam API to change features via strings
    # because we are programming generically
    for i in range(cameras.GetSize()):
        cameras[i].GetNodeMap().GetNode("Width").SetValue(640)
Exemple #16
0
def main():
    tlFactory = pylon.TlFactory.GetInstance()

    devices = tlFactory.EnumerateDevices()
    if len(devices) == 0:
        raise Exception("No basler cameras found.")

    cameras = pylon.InstantCameraArray(2)

    leftCameraFound = False
    rightCameraFound = False
    camerasFound = False

    for d in devices:
        cam = pylon.InstantCamera(tlFactory.CreateDevice(d))
        dInfo = cam.GetDeviceInfo()
        friendlyName = dInfo.GetFriendlyName()
        manfactureinfo = dInfo.GetModelName()
        if (manfactureinfo == "acA2440-20gm"):
            if (friendlyName == "phobos_nuclear_r (22864912)"):
                leftCameraFound = True
                leftDev = d
                print("left camera found")

            elif (friendlyName == "phobos_nuclear_l (22864917)"):
                rightCameraFound = True
                rightDev = d
                print("right camera found")
    if (leftCameraFound and rightCameraFound):
        camerasFound = True
        print("stereo cameras found")

    if (camerasFound):
        for i, cam in enumerate(cameras):
            if (i == 0):
                cam.Attach(tlFactory.CreateDevice(leftDev))
            elif (i == 1):
                cam.Attach(tlFactory.CreateDevice(rightDev))

        cv2.namedWindow('stereoBaslerCameras', cv2.WINDOW_NORMAL)
        cv2.namedWindow('stereoBaslerCameras (With laser)', cv2.WINDOW_NORMAL)
        cv2.namedWindow('stereoBaslerCameras (No laser)', cv2.WINDOW_NORMAL)

        converter = pylon.ImageFormatConverter()
        #converter.OutputPixelFormat = pylon.PixelType_BGR8packed
        converter.OutputPixelFormat = pylon.PixelType_Mono8
        converter.OutputBitAlignment = pylon.OutputBitAlignment_MsbAligned
        cameras.StartGrabbing()
        firstImageReceivedR = False
        firstImageReceivedR_laser = False
        firstImageReceivedR_no_laser = False
        firstImageReceivedL = False
        firstImageReceivedL_laser = False
        firstImageReceivedL_no_laser = False

        while cameras.IsGrabbing():
            grabResult = cameras.RetrieveResult(
                5000, pylon.TimeoutHandling_ThrowException)

            if grabResult.GrabSucceeded():
                cameraContextValue = grabResult.GetCameraContext()
                # Access the image data.
                #img = grabResult.Array
                # Convert to opencv image
                image = converter.Convert(grabResult)

                frame = image.GetArray()

                friendlyName = cameras[cameraContextValue].GetDeviceInfo(
                ).GetFriendlyName()

                cameras[cameraContextValue].LineSelector.SetValue("Line1")
                line1Status = cameras[cameraContextValue].LineStatus.GetValue()
                print(friendlyName + "Line 1: " + str(line1Status))
                cameras[cameraContextValue].LineSelector.SetValue("Line3")
                line3Status = cameras[cameraContextValue].LineStatus.GetValue()
                print(friendlyName + "Line 3: " + str(line3Status))

                if (friendlyName == "phobos_nuclear_r (22864912)"):
                    frame_right = frame
                    firstImageReceivedR = True
                    if (line3Status):
                        frame_right_laser = frame
                        firstImageReceivedR_laser = True
                    else:
                        frame_right_no_laser = frame
                        firstImageReceivedR_no_laser = True

                elif (friendlyName == "phobos_nuclear_l (22864917)"):
                    frame_left = frame
                    firstImageReceivedL = True
                    if (line3Status):
                        frame_left_laser = frame
                        firstImageReceivedL_laser = True
                    else:
                        frame_left_no_laser = frame
                        firstImageReceivedL_no_laser = True

                if (not firstImageReceivedR):
                    frame_right = np.zeros(shape=frame.shape, dtype=np.uint8)

                if (not firstImageReceivedR_laser):
                    frame_right_laser = np.zeros(shape=frame.shape,
                                                 dtype=np.uint8)

                if (not firstImageReceivedR_no_laser):
                    frame_right_no_laser = np.zeros(shape=frame.shape,
                                                    dtype=np.uint8)

                if (not firstImageReceivedL):
                    frame_left = np.zeros(shape=frame.shape, dtype=np.uint8)

                if (not firstImageReceivedL_laser):
                    frame_left_laser = np.zeros(shape=frame.shape,
                                                dtype=np.uint8)

                if (not firstImageReceivedL_no_laser):
                    frame_left_no_laser = np.zeros(shape=frame.shape,
                                                   dtype=np.uint8)

                frame_joint = np.concatenate((frame_left, frame_right), axis=1)
                frame_joint_with_laser = np.concatenate(
                    (frame_left_laser, frame_right_laser), axis=1)
                frame_joint_no_laser = np.concatenate(
                    (frame_left_no_laser, frame_right_no_laser), axis=1)

                # Display image
                cv2.imshow('stereoBaslerCameras', frame_joint)
                cv2.imshow('stereoBaslerCameras (With laser)',
                           frame_joint_with_laser)
                cv2.imshow('stereoBaslerCameras (No laser)',
                           frame_joint_no_laser)
                # Close on ESC
                k = cv2.waitKey(1)
                if k == 27:
                    break

        cameras.StopGrabbing()
Exemple #17
0
'''

from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtWidgets import QInputDialog
from pyqtgraph.Qt import QtCore
from PyQt5.QtCore import pyqtSlot
import sys, time
import numpy as np
from PyQt5.QtCore import Qt, QMutex
try:
    from pypylon import pylon  # pip install pypylon: https://github.com/basler/pypylon

    tlFactory = pylon.TlFactory.GetInstance()
    devices = tlFactory.EnumerateDevices()

    cameras = pylon.InstantCameraArray(min(len(devices), 20))

except:
    print('pyplon is not installed')


def camAvailable():
    '''list of camera avialable
    '''
    items = ()
    for i, cam in enumerate(cameras):
        cam.Attach(tlFactory.CreateDevice(devices[i]))
        items = items + (str(cam.GetDeviceInfo().GetFriendlyName()), )
    return items

Exemple #18
0
def test_2can():
    # Grab_MultipleCameras.cpp
    # ============================================================================
    # This sample illustrates how to grab and process images from multiple cameras
    # using the CInstantCameraArray class. The CInstantCameraArray class represents
    # an array of instant camera objects. It provides almost the same interface
    # as the instant camera for grabbing.
    # The main purpose of the CInstantCameraArray is to simplify waiting for images and
    # camera events of multiple cameras in one thread. This is done by providing a single
    # RetrieveResult method for all cameras in the array.
    # Alternatively, the grabbing can be started using the internal grab loop threads
    # of all cameras in the CInstantCameraArray. The grabbed images can then be processed by one or more
    # image event handlers. Please note that this is not shown in this example.
    # ============================================================================

    os.environ["PYLON_CAMEMU"] = "2"

    # Number of images to be grabbed.
    countOfImagesToGrab = 10 * 4

    # Limits the amount of cameras used for grabbing.
    # It is important to manage the available bandwidth when grabbing with multiple cameras.
    # This applies, for instance, if two GigE cameras are connected to the same network adapter via a switch.
    # To manage the bandwidth, the GevSCPD interpacket delay parameter and the GevSCFTD transmission delay
    # parameter can be set for each GigE camera device.
    # The "Controlling Packet Transmission Timing with the Interpacket and Frame Transmission Delays on Basler GigE Vision Cameras"
    # Application Notes (AW000649xx000)
    # provide more information about this topic.
    # The bandwidth used by a FireWire camera device can be limited by adjusting the packet size.
    maxCamerasToUse = 2

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

    try:

        # Get the transport layer factory.
        tlFactory = pylon.TlFactory.GetInstance()

        # Get all attached devices and exit application if no device is found.
        devices = tlFactory.EnumerateDevices()
        if len(devices) == 0:
            raise pylon.RuntimeException("No camera present.")

        # Create an array of instant cameras for the found devices and avoid exceeding a maximum number of devices.
        cameras = pylon.InstantCameraArray(min(len(devices), maxCamerasToUse))

        l = cameras.GetSize()

        # Create and attach all Pylon Devices.
        for i, cam in enumerate(cameras):
            cam.Attach(tlFactory.CreateDevice(devices[i]))

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

        # Starts grabbing for all cameras starting with index 0. The grabbing
        # is started for one camera after the other. That's why the images of all
        # cameras are not taken at the same time.
        # However, a hardware trigger setup can be used to cause all cameras to grab images synchronously.
        # According to their default configuration, the cameras are
        # set up for free-running continuous acquisition.
        cameras.StartGrabbing()

        # Grab c_countOfImagesToGrab from the cameras.
        for i in range(countOfImagesToGrab):
            if not cameras.IsGrabbing():
                break

            grabResult = cameras.RetrieveResult(
                5000, pylon.TimeoutHandling_ThrowException)

            # When the cameras in the array are created the camera context value
            # is set to the index of the camera in the array.
            # The camera context is a user settable value.
            # This value is attached to each grab result and can be used
            # to determine the camera that produced the grab result.
            cameraContextValue = grabResult.GetCameraContext()

            # Print the index and the model name of the camera.
            print("Camera ", cameraContextValue, ": ",
                  cameras[cameraContextValue].GetDeviceInfo().GetModelName())

            # Now, the image data can be processed.
            print("GrabSucceeded: ", grabResult.GrabSucceeded())
            print("SizeX: ", grabResult.GetWidth())
            print("SizeY: ", grabResult.GetHeight())
            img = grabResult.GetArray()
            print("Gray value of first pixel: ", img[0, 0])

    except genicam.GenericException as e:
        # Error handling
        print("An exception occurred.", e.GetDescription())
        exitCode = 1

    # Comment the following two lines to disable waiting on exit.
    sys.exit(exitCode)
Exemple #19
0
from pypylon import pylon, genicam

tlFactory = pylon.TlFactory.GetInstance()
devices = tlFactory.EnumerateDevices()
cameraArray = pylon.InstantCameraArray(len(devices))

for i, camera in enumerate(cameraArray):
    camera.Attach(tlFactory.CreateDevice(devices[i].GetFullName()))
    camera.Open()
    camera.RegisterConfiguration(pylon.SoftwareTriggerConfiguration(), pylon.RegistrationMode_ReplaceAll,
                             pylon.Cleanup_Delete)
    
    pylon.FeaturePersistence.Load(nodeFile, camera.GetNodeMap(), True)
    # camera[i].TriggerSelector = "FrameBurstStart" # <== Selector first!
    # camera[i].TriggerSource = "Line3"
    # camera[i].TriggerMode = 'On'

    # camera[i].LineSelector = "Line3"
    # camera[i].LineMode = "Input"

    # camera.Open()

    camera.StartGrabbing(pylon.GrabStrategy_OneByOne, pylon.GrabLoop_ProvidedByInstantCamera)

    print(camera.GetDeviceInfo())
    print(camera.ExposureTime.camera.GetValue())

camera.WaitForFrameTriggerReady(1000)
Exemple #20
0
import cv2

# preface
exitCode = 0
maxCamerasToUse = 4
countOfImagesToGrab = 1
try:

    # get the transport layer factory
    tlFactory = pylon.TlFactory.GetInstance()

    devices = tlFactory.EnumerateDevices()
    if len(devices) == 0:
        raise pylon.RUNTIME_EXCEPTION("No camera present")

    cameras = pylon.InstantCameraArray(min(len(devices), maxCamerasToUse))

    for ii, cam in enumerate(cameras):
        cam.Attach(tlFactory.CreateDevice(devices[ii]))

        print(cam.GetDeviceInfo().GetModelName(), "-",
              cam.GetDeviceInfo().GetSerialNumber())

        # set parameters
        # pixel format
        print(cam.PixelFormat.GetValue())
        cam.PixelFormat.SetValue("Mono12")
        print(cam.PixelFormat.GetValue())
        # exposure time
        cam.ExposureAuto.SetValue("Off")
        cam.ExposureTime.SetValue(100.0)
Exemple #21
0
def parameterize_cameras(number_of_cameras, list_of_setting_lists):
    '''
    Int: number_of_cameras, number of cameras attached to computer
    
    List: list_of_setting_lists, [[pixel_format, exposure, gain, fps],[...], ... ,[...]] sets capture parameters for each camera
    must have the same number of sub-lists as 'number_of_cameras' 
    sublists must have the format of [pixel_format, exposure, gain, fps]
    
    '''

    #Get the transport layer factory.
    tlFactory = pylon.TlFactory.GetInstance()

    #Get all attached devices and exit application if no device is found.
    devices = tlFactory.EnumerateDevices()
    if len(devices) == 0:
        raise pylon.RUNTIME_EXCEPTION("No camera present.")

    #Create an array of instant cameras for the found devices and avoid exceeding a maximum number of devices.
    cameras = pylon.InstantCameraArray(min(len(devices), number_of_cameras))
    #l = cameras.GetSize()
    try:
        for i, cam in enumerate(cameras):

            a = list_of_setting_lists[i]
            pixel_format = a[0]
            exposure = a[1]
            gain = a[2]
            fps = a[3]

            cam.Attach(tlFactory.CreateDevice(devices[i]))

            cam.Open()

            print('camera ' + str(i) + ' model name')
            cam_info = cam.GetDeviceInfo().GetModelName(
            ), "-", cam.GetDeviceInfo().GetSerialNumber()
            cam_info = cam_info[0] + cam_info[1] + cam_info[2]
            print(cam_info)

            cam.PixelFormat.SetValue(pixel_format)
            cam.ExposureTime.SetValue(exposure)
            cam.Gain.SetValue(gain)
            cam.AcquisitionFrameRateEnable.SetValue(True)
            cam.AcquisitionFrameRate.SetValue(fps)

            print('pixel format, exposure, gain, fps')
            spec = pixel_format + ', ' + str(exposure) + ', ' + str(
                gain) + ', ' + str(fps)
            print(spec)
            print('resulting frame rate')
            cam_info = str(cam.ResultingFrameRate.GetValue())
            print(cam_info)

            # Print the model name of the camera.
            cam_info = cam.GetDeviceInfo().GetModelName()
            cam.Close()
    except genicam.GenericException as e:
        # Error handling
        print("An exception occurred.", str(e))
        cameras.Close()

    return cameras