Continuous high-speed capture
This sample receives 1,000 fps images from the INFINICAM GbE-2 for 5 seconds without throwing any away, and decodes them. It counts and shows the number of frames received and the number of dropped frames (frames that did not arrive). It is the foundation for programs that need to analyze every 1,000 fps image.
-
Enter and save the program
Save the following code as
continuous_capture.pyinC:\infinicam_projects\python.import queueimport threadingimport timefrom pypuclib import CameraFactory, PUCExceptionFRAMERATE = 1000 # Frame rate [fps]SECONDS = 5 # How long to keep receiving [s]print("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)# Set the frame rate (set here because the camera may still have the settings from its last use)cam.setFramerateShutter(FRAMERATE, FRAMERATE)reso = cam.resolution()# Prepare the decoder and have it decode with 4 threads in paralleldecoder = cam.decoder()decoder.setNumDecodeThread(4)# Warm up by decoding one frame first (the first decode takes time to set up,# which delays receiving and causes dropped frames)decoder.decode(cam.grab())# Queue that hands received data over to the decoding side (up to 1000 frames = 1 second)frames = queue.Queue(maxsize=1000)# Countersstats = {"received": 0, "gaps": 0, "damaged": 0, "overflow": 0, "decoded": 0}last_seq = Nonedef on_frame(xfer):"""Called every time a frame arrives. Do nothing heavy here: just put it in the queue"""global last_seqstats["received"] += 1# If the sequence number skips, the skipped frames were droppedseq = xfer.sequenceNo()if last_seq is not None:stats["gaps"] += ((seq - last_seq) & 0xFFFF) - 1last_seq = seqif xfer.isDamaged():stats["damaged"] += 1returntry:frames.put_nowait(xfer.data().copy())except queue.Full:stats["overflow"] += 1 # Decoding could not keep up and the queue overfloweddef decode_worker():"""Takes data out of the queue and decodes it (runs in a separate thread)"""while True:data = frames.get()if data is None: # Signal to finishbreakimage = decoder.decode(data, reso)stats["decoded"] += 1# Write the code that analyzes image (a NumPy array) hereworker = threading.Thread(target=decode_worker)worker.start()print(f"Receiving at {FRAMERATE} fps for {SECONDS} seconds...")cam.setRingBufferCount(64)start = time.perf_counter()cam.beginXfer(on_frame)time.sleep(SECONDS)elapsed = time.perf_counter() - startcam.endXfer()frames.put(None) # Tell the decoding side to finishworker.join()cam.close()print(f"Frames received : {stats['received']} ({stats['received'] / elapsed:.0f} fps)")print(f"Dropped frames : {stats['gaps']}")print(f"Damaged frames : {stats['damaged']}")print(f"Queue overflows : {stats['overflow']}")print(f"Frames decoded : {stats['decoded']}") -
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 continuous_capture.pyAfter about 5 seconds you see output like the following. If dropped frames, damaged frames, and queue overflows are all 0, and frames received equals frames decoded, you processed the 1,000 fps images without throwing a single one away.
Connecting to the camera...Receiving at 1000 fps for 5 seconds...Frames received : 4999 (999 fps)Dropped frames : 0Damaged frames : 0Queue overflows : 0Frames decoded : 4999
How the program works
Section titled “How the program works”1. Split receiving and decoding into separate jobs
Section titled “1. Split receiving and decoding into separate jobs”This program has 2 jobs running at the same time.
| Job | Function | What it does |
|---|---|---|
| Receiving | on_frame |
Called every time a frame arrives; puts a copy of the data in the queue |
| Decoding | decode_worker |
Takes data out of the queue and decodes it (runs in a separate thread) |
on_frame is called 1,000 times per second, so each call must finish in less than 1 ms. If you did the heavy decoding inside on_frame, receiving the next frame would be delayed and frames would be dropped. So on_frame only “puts data in the queue”, and decoding is left to the other job.
2. The queue (queue.Queue)
Section titled “2. The queue (queue.Queue)”frames = queue.Queue(maxsize=1000)frames.put_nowait(data) # Put in (receiving side)data = frames.get() # Take out (decoding side)queue.Queue is a “queue” for handing data between threads safely. Items come out in the order they went in. Even if decoding falls behind for a moment, data just piles up in the queue and is not thrown away.
maxsize=1000means it can hold up to 1,000 frames (1 second’s worth).put_nowait()raises an error (queue.Full) instead of waiting when the queue is full. It puts data in without waiting so the receiving job is never held up.- At the end,
Noneis put in the queue to tell the decoding job to “finish”.
3. Decode in parallel
Section titled “3. Decode in parallel”decoder.setNumDecodeThread(4)This splits the decoding of each frame across 4 threads. An 800 × 600 image decodes in about 0.6 ms, which keeps up with 1,000 fps (1 ms per frame).
4. Count dropped frames
Section titled “4. Count dropped frames”seq = xfer.sequenceNo()stats["gaps"] += ((seq - last_seq) & 0xFFFF) - 1The camera attaches a sequence number to each captured image. If the number that arrives is 2 or more ahead of the previous one, you know the images in between did not arrive (were dropped). & 0xFFFF keeps the calculation correct when the number wraps from its maximum (65535) back to 0.
5. The ring buffer
Section titled “5. The ring buffer”cam.setRingBufferCount(64)This is the number of slots (the ring buffer) where pypuclib temporarily holds incoming data. Even if on_frame is delayed for a moment, up to 64 frames (64 ms at 1,000 fps) can wait here.
