From 695361e04e83f800cc1c7488dc7f20239ea08de3 Mon Sep 17 00:00:00 2001
From: mhoeschle <mhoeschle>
Date: Wed, 12 Jul 2023 17:20:42 +0200
Subject: [PATCH] Modyfied whole code to run with several connected cameras

---
 BaslerChangeParameter.py | 222 +++++++++++++++++----------------------
 1 file changed, 98 insertions(+), 124 deletions(-)

diff --git a/BaslerChangeParameter.py b/BaslerChangeParameter.py
index 1b4e0c7..cdf9553 100644
--- a/BaslerChangeParameter.py
+++ b/BaslerChangeParameter.py
@@ -2,153 +2,135 @@ import pypylon.pylon as py
 from pypylon import pylon
 import numpy as np
 import matplotlib.pyplot as plt
+from pypylon import genicam
+import sys
 import time
+import os
 
 #
 # Variable:
 #
 
-camera = pylon.InstantCamera()
+# Max Number of cameras that should be used
+MAXCAMERASTOUSE = 2
 
-COLCAMNAMES = {
-    '22320672': 'acA2000-165uc',
-    '24531290': 'acA1920-40uc',
-    '24531319': 'acA1920-40uc',
-}
 
+# Get the transport layer factory.
+tlFactory = pylon.TlFactory.GetInstance()
 
-"""
-Function 
-"""
+# 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. -> Output-> Pylon::CInstantCameraArray
+CAMERAS_ARRAY = pylon.InstantCameraArray(min(len(devices), MAXCAMERASTOUSE))
+print(f'cameras: {CAMERAS_ARRAY}')
+
+l = CAMERAS_ARRAY.GetSize()
 
 #
-# list all the connected cameras at the system:
+# Funktions:
 #
 
+# List all connected / founded cameras:
 
-def listcam():
-    """ 
-        schows all connected Basler cameras
-    """
-    # Generates a list of the cameras connected to our computer, like what we see with the PylonViewer program
 
-    tl_factory = pylon.TlFactory.GetInstance()
-    # print(tl_factory)
+def listcams():
+    '''
+    shows all connected / founded cameras. Number of cameras is defined by CAMERAS_ARRAY
+    '''
 
-    devices = tl_factory.EnumerateDevices()
-    # print(devices)
+    # Create and attach all Pylon Devices.
+    for i, camera_instantz in enumerate(CAMERAS_ARRAY):
+        # cam is an instance Swig object of type Pylon::CInstantCamera on cluster on HD
+        camera_instantz.Attach(tlFactory.CreateDevice(devices[i]))
+        print(f'camInstatnt: {type(camera_instantz)}')
 
-    allcam = []
+    #
+    # list all the connected cameras at the system:
+    #
 
-    for device in devices:
-        print("Device Input (Camera Type & (Serialnumber)):")
-        # Model name + Serial number
-        print("-", device.GetFriendlyName(), "\n")
-        #print("-", device.GetModelName())
-        #print("-", device.GetSerialNumber(), "\n")
-        allcam.append(device.GetFriendlyName())
+        # Print the model name of the camera.
+        cam_ids = camera_instantz.GetDeviceInfo().GetSerialNumber()
+        print("Using device ", cam_ids)
 
-    return allcam
+    return cam_ids, camera_instantz
 
+# Open cameras:
 
-# foundcams retrun a list with all connected cameras.
-#foundcams = listcam()
 
-# for cam in foundcams:
-    #print(f'found cam: {cam}')
+def opencams():
+    '''
+    open camera to read or write values
+    '''
+    CAMINSTANT.Open()
+    print(f'Cam open: {CAM_ID}', '\n')
 
+# Close cameras:
 
-#
-# open camara device
-#
 
+def closecams():
+    '''
+    close camera after read or write values
+    '''
+    CAMINSTANT.Close()
+    print(f'Cam close: {CAM_ID}', '\n')
 
-def opencam():
-    """ 
-        opens interface to camera
-        Creates an instant camera object with the camera device found first.
-    """
-    #
-    # camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())
-    # open camera, crate a device!
-    #
-    print("openDevice:", "\n")
-    return camera.Open()
+# read camera parameters to get an current overiew
 
-# opencam()
 
-#
-# close camera interface
-#
-
-
-def closecam():
-    """ 
-        close interface to camera
+def readcams():
     """
-    # close camera
-    ## camera = pylon.InstantCamera(pylon.TlFactory.GetInstance().CreateFirstDevice())
-    print("closeDevice:", "\n")
-    return camera.Close()
-# closecam()
-
-#
-# read parameters in camara
-#
-
-
-def readcam():
-    """ 
         read out current settings from camera via interface
     """
-    # open camera interface:
-    opencam()
-
+    opencams()
     # Read Gain value in Camera:
     print("Gain in (dB):")
     # Gain value
-    print(camera.Gain.Value, "\n")
+    print(CAMINSTANT.Gain.GetValue(), "\n")
 
     # Read Trigger Delay value in Camera:
     print("Delay in (microseconds):")
     # TriggerDelay value
-    print(camera.TriggerDelay.Value, "\n")
+    print(CAMINSTANT.TriggerDelay.GetValue(), "\n")
 
     # Exposure parameter
-    oldexposure = camera.ExposureTime.GetValue()
+    oldexposure = CAMINSTANT.ExposureTime.GetValue()
     print(f'exposure: {oldexposure}', "\n")
 
-    oldfps = camera.AcquisitionFrameRate.GetValue()
+    oldfps = CAMINSTANT.AcquisitionFrameRate.GetValue()
     print(f'fps: {oldfps}')
 
     # Gamma value:
     print("Camera gamma value: ")
-    print(camera.Gamma.GetValue(), "\n")
+    print(CAMINSTANT.Gamma.GetValue(), "\n")
 
-    # closecam()
+    closecams()
 
+# readcam()
 
 #
 # Funktion for changing the value (uncomment the comment in the next line (camera.Gain = YourValue))
 #
+
+
 def gaincam():
-    """ 
-        changes the gain in (dB) 
     """
-    opencam()
+        changes the gain in (dB). Entering float numbers for. e.g: 5.0
+    """
+
     # Read Gain value in Camera:
     print(" Gain in (dB):")
     # Gain value
-    print(camera.Gain.Value, "\n")
+    print(CAMINSTANT.Gain.GetValue(), "\n")
     # Input new gain value
     gainvalue = float(input("Please enter the new gain in (dB): "))
-    camera.Gain = (gainvalue)
+    CAMINSTANT.Gain.SetValue(gainvalue)
     # Read Gain value in Camera:
     print("New Gain in (dB):")
     # Gain value
-    print(camera.Gain.Value, "\n")
-    closecam()
-
+    print(CAMINSTANT.Gain.GetValue(), "\n")
 
 # gaincam()
 
@@ -158,25 +140,21 @@ def gaincam():
 
 
 def exposurecam():
-    """ 
+    """
         changes the exposure time in microseconds (ms)
     """
-    opencam()
 
-    oldexposure = camera.ExposureTime.GetValue()
+    oldexposure = CAMINSTANT.ExposureTime.GetValue()
     print(f'old exposure: {oldexposure}')
 
     newexposure = input("Please enter new exposure value (microseconds): ")
     newexposure = float(newexposure)
-    camera.ExposureTime.SetValue(newexposure)
+    CAMINSTANT.ExposureTime.SetValue(newexposure)
 
     # Read new exosure value in Camera:
     print("New exposure in (ms):")
     # print new exposure value
-    print(camera.ExposureTime.GetValue(), "\n")
-
-    closecam()
-
+    print(CAMINSTANT.ExposureTime.GetValue(), "\n")
 
 # exposurecam()
 
@@ -186,86 +164,82 @@ def exposurecam():
 
 
 def aquisationfps():
-    """ 
-        enable / dissable auto or manual fps and 
-        changes the fps (frame per seconds)  
     """
-    opencam()
-    status = camera.AcquisitionFrameRateEnable.GetValue()
+        enable / dissable auto or manual fps and
+        changes the fps (frame per seconds)
+    """
+
+    status = CAMINSTANT.AcquisitionFrameRateEnable.GetValue()
     print(f'fps enable? {status}')
 
     statusenable = str(input("Do you want to change fps, (y/n)? "))
 
     if statusenable.lower() == 'y':
-        camera.AcquisitionFrameRateEnable.SetValue(True)
-        oldfps = camera.AcquisitionFrameRate.GetValue()
+        CAMINSTANT.AcquisitionFrameRateEnable.SetValue(True)
+        oldfps = CAMINSTANT.AcquisitionFrameRate.GetValue()
         print(f'Old fps: {oldfps}')
 
         newfps = input("Choose your fps: ")
-        camera.AcquisitionFrameRate.SetValue(float(newfps))
+        CAMINSTANT.AcquisitionFrameRate.SetValue(float(newfps))
 
         print(f"New fps is: {newfps}", '\n')
 
     else:
         print("disabled Aquisation Frame rate!")
-        camera.AcquisitionFrameRateEnable.SetValue(False)
-
-    closecam()
+        CAMINSTANT.AcquisitionFrameRateEnable.SetValue(False)
 
 # aquisationfps()
 
-
 #
 # Funktion for changing the trigger delay in microseconds (e.g. 2000 ms ):
 #
 
+
 def triggerdelaycam():
-    """ 
+    """
         changes the trigger delay in microseconds (ms)
     """
-    opencam()
-    print(f'trigger delay is: {camera.TriggerDelay.GetValue()}')
+
+    print(f'trigger delay is: {CAMINSTANT.TriggerDelay.GetValue()}')
 
     newtriggerdelay = input(
         "Please enter new trigger delay in (microseconds): ")
 
-    camera.TriggerDelay.SetValue(float(newtriggerdelay))
+    CAMINSTANT.TriggerDelay.SetValue(float(newtriggerdelay))
 
-    print(f'New trigger delay is: {camera.TriggerDelay.GetValue()}')
-
-    closecam()
+    print(f'New trigger delay is: {CAMINSTANT.TriggerDelay.GetValue()}')
 
 # triggerdelaycam()
 
-
 # How to show the images ?
 # Next step
 # start canera in free run mode:
+
+
 def freeruncam():
+    '''
+# grabbing images in free run
+'''
 
     # camera start free run mode: VIDEO 37:32
-    camera.StartGrabbing(pylon.GrabStrategy_OneByOne)
+    CAMINSTANT.StartGrabbing(pylon.GrabStrategy_OneByOne)
     i = 0
     print('Starting to acquire')
     t0 = time.time()
-    while camera.IsGrabbing():
-        grab = camera.RetrieveResult(100, pylon.TimeoutHandling_ThrowException)
+    while CAMINSTANT.IsGrabbing():
+        grab = CAMINSTANT.RetrieveResult(
+            100, pylon.TimeoutHandling_ThrowException)
         if grab.GrabSucceeded():
             i += 1
         if i == 100:
+            CAMINSTANT.StopGrabbing()
             break
 
     print(f'Acquired {i} frames in {time.time()-t0:.0f} seconds')
 
 
-# freeruncam()
-
 # ---> ongoing, not yet in usage.
 
-
 if __name__ == '__main__':
-    foundcams = listcam()
-    for cam in foundcams:
-        print(f'found cam: {cam}')
-
-    readcam()
+    CAM_ID, CAMINSTANT = listcams()
+    readcams()
-- 
GitLab