alliedvision / VimbaPython

Old Allied Vision Vimba Python API. The successor to this API is VmbPy
BSD 2-Clause "Simplified" License
93 stars 40 forks source link

How to run the asynchronous mode infinitely in Allied Vision Vimba SDK camera? #179

Closed reemastha706 closed 6 months ago

reemastha706 commented 6 months ago

Hi, I am want to do image acquisition to get the maximum intensity value at certain time. This loop needs to run infinitely until the user wants to terminate the loop. my algorithm is as follow:

  1. start camera
  2. stacking the frame values in array for 'x' seconds and averaging the frame values
  3. calculate the max value of the stacked array
  4. take a pause(1 sec) for example,
  5. reset the original stack array values
  6. repeat 2.
  7. if keyboard pressed 'q', break the loop
  8. cam stop

This is my code:

import time
from vimba import*
import os
import cv2
import datetime
import numpy as np
import keyboard
def frame_handler(cam, frame):
    global image_arr
    cam.queue_frame(frame)

    image = frame.as_opencv_image()
    image_arr += image.astype(float)

def max_val(image_arr, num):
    return np.max(image_arr/num)

image_arr = np.zeros((1024, 1280,1))

with Vimba.get_instance() as vimba:
    cams = vimba.get_all_cameras()
    with cams[0] as cam:
        try: 
            cam.start_streaming(frame_handler)

            while True:
                time.sleep(0.1)
                val = max_val(image_arr, 4)
                print(val)

                time.sleep(0.1)
                image_arr = np.zeros((1024, 1280,1))

                if keyboard.read_key() == 'q':
                    break

        finally:
            cam.stop_streaming()

But this is not running properly. either the code crashes or the value it reads is wrong. How do I solve this problem?

reemastha706 commented 6 months ago

I found a solution for my problem from one of the other post. Thanks :)

Teresa-AlliedVision commented 6 months ago

Hi, that's great to hear. Can you link the solution, in case others find this issue and have a similar application?

reemastha706 commented 6 months ago

I just did a slight modification on Niklas's code https://github.com/alliedvision/VimbaPython/issues/62 instead of write_image() `def stack(img_arr, frame): img_arr += frame return img_arr

def maxvalue(frame_queue: queue.Queue): while True: img_arr = np.zeros((1024, 1280, 1)) pause = 1 #in sec start_time = time.time() count = 0 while time.time() - start_time < pause: frame, id = frame_queue.get() img_arr = stack(img_arr, frame.astype(float)) count += 1 print(f'Max value: {np.round(np.max(img_arr)/count, 2)}') #count give the number of frames prcoessed
frame_queue.task_done() ` and changed the for loop in record image with while loop. Even though, i couldn't do much about user input stopping of camera but Ctrl+C (keyboard interruption, works fine for now.