OpenCV LiveView
This sample keeps receiving images from the INFINICAM GbE-2 at 1,000 fps and shows them in an OpenCV window in real time (live view). The top-left corner of the window shows how many frames were received in the last second.
-
Enter and save the program
Save the following code as
opencv_live.pyinC:\infinicam_projects\python.import threadingimport timeimport cv2from pypuclib import CameraFactory, PUCExceptionprint("Connecting to the camera...")try:# Connect to the GbE-2 at this IP addresscam = CameraFactory().create(ip="192.168.0.10")except PUCException as e:print("Error: could not connect to the camera.", e)raise SystemExit(1)# Capture at 1000 fps with a 1/1000 s shutter (set here because the camera may still have the settings from its last use)cam.setFramerateShutter(1000, 1000)reso = cam.resolution()decoder = cam.decoder()# Where the newest frame from the camera and the number of frames received are keptlatest = Nonereceived = 0lock = threading.Lock()def on_frame(xfer):"""Called by pypuclib every time a frame arrives (a callback)"""global latest, receivedif xfer.isDamaged():return # Skip data that arrived incompletedata = xfer.data().copy() # The contents are overwritten after this function returns, so keep a copywith lock:latest = datareceived += 1window = "INFINICAM LiveView (ESC or Q to quit)"cv2.namedWindow(window, cv2.WINDOW_AUTOSIZE)# Start continuous transfer (on_frame is called every time a frame arrives)cam.beginXfer(on_frame)print("Live view running... Select the video window and press ESC or Q to exit.")try:last_time = time.perf_counter()last_count = 0fps_text = ""while True:with lock:data = latestlatest = Nonecount = receivedif data is not None:# Decode and show only the newest frame (not every frame that arrived)image = decoder.decode(data, reso)cv2.putText(image, fps_text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, 255, 2)cv2.imshow(window, image)# Every second, work out how many frames arrived in the last secondnow = time.perf_counter()if now - last_time >= 1.0:fps_text = f"receive: {(count - last_count) / (now - last_time):.0f} fps"last_time, last_count = now, countkey = cv2.waitKey(1) & 0xFFif key in (27, ord("q"), ord("Q")): # ESC or Qbreakfinally:# Stop continuous transfer, then close the cameracam.endXfer()cam.close()cv2.destroyAllWindows()print(f"Done (frames received: {received}).") -
Run it
Run the following 2 lines, one at a time, in Command Prompt (or PowerShell).
Terminal window cd C:\infinicam_projects\pythonTerminal window python opencv_live.pyIf a window opens with moving video from the camera and the top-left corner shows something like
receive: 1000 fps, it worked. -
Exit
Click the video window to select it, then press
ESCorQon the keyboard to exit. Pressing the keys while the black Command Prompt window is selected does not exit.Connecting to the camera...Live view running... Select the video window and press ESC or Q to exit.Done (frames received: 3214).
How the program works
Section titled “How the program works”1. Continuous transfer and callbacks
Section titled “1. Continuous transfer and callbacks”def on_frame(xfer): ...
cam.beginXfer(on_frame)When you start continuous transfer with cam.beginXfer(), the camera sends captured images one after another. Every time a frame arrives, pypuclib calls the function you passed in (here, on_frame). A function that is “called for you when something happens” like this is called a callback.
on_frameis called 1,000 times per second, so it is important not to do heavy work inside it. Here it just copies the received data and stores it inlatest.xfer.isDamaged()isTruewhen part of the data did not arrive (the frame is incomplete).- The contents of
xfer.data()are overwritten by the next frame afteron_framereturns..copy()keeps a copy to use later.
2. Show only the newest frame
Section titled “2. Show only the newest frame”with lock: data = latest latest = NoneThe screen can only refresh a few dozen times per second. Trying to show all 1,000 frames would not keep up, so right before showing, the program takes out only the newest frame, decodes it, and shows it. The key idea is to think of receiving (1,000 fps) and displaying (a few dozen fps) separately.
3. Locks
Section titled “3. Locks”lock = threading.Lock()
with lock: ...on_frame is called from a different thread (a separate flow running at the same time) than the main program. If 2 flows write and read latest at the same time, its contents can get mixed up. Only one flow at a time can be inside with lock:, so the data is handed over safely.
4. The order of shutting down
Section titled “4. The order of shutting down”cam.endXfer()cam.close()Stop continuous transfer with endXfer(), then close the camera with close(). Because these are under finally:, the program cleans up in this order even if it stops with an error.
