Python Barcode Scanner for Windows, Linux, and macOS (OpenCV + Capture Vision)
A Python barcode scanner on Windows, Linux, or macOS needs only two pieces: OpenCV opens the webcam (or loads an image file) and hands over raw pixel buffers, while Dynamsoft Capture Vision’s CaptureVisionRouter decodes every 1D and 2D symbol in those buffers. For a still image the whole job is one capture() call; for a live stream the same router runs asynchronously through ImageSourceAdapter and CapturedResultReceiver, so the Python main thread stays free to draw the OpenCV preview. OpenCV never decodes a barcode and the SDK never opens a camera — keeping that split explicit is what makes one code path work on all three desktop platforms.
Install dynamsoft-capture-vision-bundle (3.6.5000) and opencv-python, activate a trial license, and the smallest working file scanner is about ten lines. Measured on Windows 11 with Python 3.14.4 for this refresh: one capture() call returned 19 barcodes from a 1456 × 1484 test sheet in 77.6 ms at steady state, and a paced 30 fps camera stream produced one result callback per submitted frame. The full GitHub sample adds overlay drawing, a GUI and multi-page PDF decoding; the two core paths below are the parts that actually read barcodes.
What you’ll build: A cross-platform Python barcode and QR code scanner that decodes barcodes from static images and live webcam streams on Windows, Linux, and macOS using OpenCV and Dynamsoft Capture Vision.
Key Takeaways
- OpenCV owns frame acquisition and display;
CaptureVisionRouterowns decoding.capture()handles files, whilestart_capturing()with anImageSourceAdapterhandles live webcam frames. dynamsoft-capture-vision-bundle3.6.5000 and the barcode-onlydynamsoft-barcode-reader-bundle11.6.5000 expose the sameLicenseManager/CaptureVisionRouterAPI. The GitHub sample imports the latter, so switching packages changes only the import line.- Measured 2026-11-12 on Windows 11 / Python 3.14.4: 19 codes from
multi.png(1456 × 1484) in 77.6 ms median steady state, 65 QR codes frommulti-qr.png(989 × 1074) in 75.2 ms, and one QR code fromnormal.jpg(1024 × 524) in 13.0 ms. The first call in a fresh process is slower (138.0 ms and 81.3 ms respectively) because the engine initializes. - At a paced 30 fps, 300 submitted frames produced 299 result callbacks in 10 s. Saturating the input at 563.9 frames/s produced 320.5 result callbacks/s — the SDK’s bounded buffer drops excess frames instead of growing an unbounded queue.
- Shut down in order:
cvr.stop_capturing()→vc.release()→cv2.destroyAllWindows(), then drain the result queue. One late callback still arrived afterstop_capturing()in the 10-second run.
Common Developer Questions
How do I read QR codes and barcodes from a webcam in Python on Windows, Linux, or macOS?
Read frames with cv2.VideoCapture(0), convert each frame to ImageData and push it into an ImageSourceAdapter, then call CaptureVisionRouter.start_capturing(EnumPresetTemplate.PT_READ_BARCODES.value). A CapturedResultReceiver receives decoded barcodes on the SDK’s native worker thread; a queue.Queue hands them back to the main thread for drawing. The API is identical on all three desktop platforms.
What Python library can decode multiple barcodes from a single image?
dynamsoft-capture-vision-bundle decodes multiple 1D and 2D barcodes from one image with CaptureVisionRouter.capture(path, PT_READ_BARCODES); result.get_items() returns one BarcodeResultItem per code, each with get_format_string(), get_text() and a four-point get_location(). On the 1456 × 1484 multi.png test sheet this returned 19 items in a single call, including CODE_128, EAN_13, QR_CODE, PDF417, DATAMATRIX, AZTEC, MAXICODE and Micro QR.
How do I integrate the Dynamsoft Capture Vision SDK with OpenCV for real-time barcode scanning?
Convert the OpenCV BGR matrix with ImageData(mat.tobytes(), width, height, width * channels, EnumImagePixelFormat.IPF_RGB_888) and call fetcher.add_image_to_buffer() once per vc.read(). Both raw BGR bytes and RGB-corrected bytes returned the same 19 items on the test sheet, because barcode decoding works on luminance. Keep all cv2.imshow() and cv2.drawContours() work in the main thread.
Which Python and SDK versions are tested for Windows, Linux, and macOS?
The measured run used Windows 11 (build 26200, AMD64), Python 3.14.4, opencv-python 5.0.0.93 and dynamsoft-capture-vision-bundle 3.6.5000. Version 3.6.5000 publishes CPython 3.10–3.14 wheels for win_amd64, manylinux2014_x86_64, manylinux_2_28_aarch64 and macosx_12_0_universal2 (published 2026-10-29); dynamsoft-barcode-reader-bundle 11.6.5000 ships the matching wheel set. The sample repository’s CI runs on ubuntu-latest with Python 3.12 and DCV 3.6.5000.
How many frames per second can the Python webcam scanner process?
On the measured Windows machine the USB camera reported 30 fps at 640 × 480 through the MSMF backend, and the loop submitted 265 frames in 10 s (26.4/s) with 265 matching result callbacks (median callback gap 31.7 ms). A paced 30 fps stream produced 299 callbacks from 300 submitted frames. Pushing 5,640 frames in 10 s produced 3,206 callbacks (320.5/s), so the observed throughput on that 640 × 480 sheet was about 320 decodes/s and the bounded buffer discards the rest.
How should I shut down the camera and the capture pipeline cleanly?
Call stop_capturing() first to stop the native worker, then vc.release() to free the camera, then cv2.destroyAllWindows(). The CapturedResultReceiver callback runs on a native thread, so it should only put results into a queue.Queue; keep the result objects alive until the main thread has consumed them, and drain the queue once more after stopping because a final in-flight callback can arrive.
Does the GitHub sample use the same package as the article?
The article uses dynamsoft-capture-vision-bundle 3.6.5000, while examples/official/camera_file in the sample repository pins dynamsoft-barcode-reader-bundle==11.6.5000 and imports from dynamsoft_barcode_reader_bundle import *. Both packages expose the same license, router, preset-template and image-source APIs, so only the import statement and the pinned version differ.
This article is Part 3 in a 4-Part Series.
- Part 1 - Python Document Edge Detection Tutorial: Detect, Auto-Crop, and Correct Document Orientation
- Part 2 - Extract Passport MRZ Data in Python on Windows, Linux, and macOS
- Part 3 - Python Barcode Scanner for Windows, Linux, and macOS (OpenCV + Capture Vision)
- Part 4 - Python OCR Tutorial: Recognize SEMI Semiconductor Fonts with Dynamsoft Capture Vision SDK
Which Path Fits Your Scanning Goal
| Input | Use this API | Result object | What your code owns |
|---|---|---|---|
| One image file (PNG/JPG) | cvr.capture(path, PT_READ_BARCODES) |
CapturedResult.get_items() |
File path, drawing the quad overlay |
| Multi-page PDF or TIFF | cvr.capture_multi_pages(path, PT_READ_BARCODES) |
CapturedResultArray.get_results(), one entry per page |
Page numbering via FileImageTag |
| Live webcam stream | cvr.set_input(fetcher), add_result_receiver(), start_capturing() |
on_captured_result_received() callback |
Camera open/read, frame conversion, queue, preview, shutdown |
All three paths return the same BarcodeResultItem fields, so recognition logic does not change when the input source changes.
The Minimal Barcode Path
This is the complete still-image scanner: one license call, one router, one capture() call, one items array.
from dynamsoft_capture_vision_bundle import (
LicenseManager, CaptureVisionRouter, EnumPresetTemplate, EnumErrorCode,
)
error_code, message = LicenseManager.init_license("LICENSE-KEY")
if error_code not in (EnumErrorCode.EC_OK, EnumErrorCode.EC_LICENSE_CACHE_USED):
raise RuntimeError(message)
cvr = CaptureVisionRouter()
result = cvr.capture("image.png", EnumPresetTemplate.PT_READ_BARCODES.value)
for item in result.get_items():
print(item.get_format_string(), item.get_text(),
[(p.x, p.y) for p in item.get_location().points])
get_format() returns an integer enum value (for example 2 for CODE_128); get_format_string() returns the readable name. For live frames, add the conversion helper and four SDK wiring calls — Step 2 has the full receiver implementation.
import cv2
from dynamsoft_capture_vision_bundle import ImageData, EnumImagePixelFormat
def convertMat2ImageData(mat):
height, width, channels = mat.shape
return ImageData(mat.tobytes(), width, height, width * channels,
EnumImagePixelFormat.IPF_RGB_888)
vc = cv2.VideoCapture(0)
ret, frame = vc.read()
if ret:
image_data = convertMat2ImageData(frame) # pass to fetcher.add_frame()
The live path is then cvr.set_input(fetcher) → cvr.add_result_receiver(receiver) → cvr.start_capturing(PT_READ_BARCODES) → fetcher.add_frame(image_data) once per frame. Everything else in the sample is overlay drawing and UI.
Measured Results
Still-image decoding, six capture() calls per file on the same CaptureVisionRouter instance. The first call in a fresh process includes engine initialization and is reported separately; “steady state” is the median of the five following calls.
| Input file | Resolution | Barcodes returned | First call | Steady state |
|---|---|---|---|---|
images/multi.png |
1456 × 1484 | 19 | 138.0 ms | 77.6 ms (75.2–89.2 ms) |
camera_file/multi-qr.png |
989 × 1074 | 65 | 81.3 ms | 75.2 ms (66.9–80.2 ms) |
images/normal.jpg |
1024 × 524 | 1 | 13.4 ms | 13.0 ms (12.7–13.6 ms) |
The 19 items on multi.png are CODE_128, CODE_93, EAN_13, AZTEC, DATAMATRIX, MICRO_PDF417, ITF, MICRO_QR, PDF417, MAXICODE, QR_CODE, EAN_8, INDUSTRIAL_25, MSI_CODE, CODABAR, CODE_39_EXTENDED (twice), UPC_A and UPC_E.
Live pipeline, each run 10 s with the same ImageSourceAdapter / CapturedResultReceiver wiring used in Step 2:
| Run | Frames submitted | Result callbacks | Barcodes decoded | Queue depth |
|---|---|---|---|---|
| Real USB camera, 640 × 480 @ 30 fps (dark frame) | 265 (26.4/s) | 265 (26.4/s) | 0 | max 3; 1 late result after stop |
| Paced 30 fps stream, one QR per frame | 300 (30.0/s) | 299 (29.9/s) | 299 | max 2 |
| Saturated stream, no pacing | 5,640 (563.9/s) | 3,206 (320.5/s) | 3,206 | max 2 |
Two behaviors follow from these numbers. At camera speed the pipeline is effectively 1:1 — one callback per frame, median callback gap 31.7 ms on the real camera — so throttling to the camera’s own frame rate is enough. Feeding frames faster than the decoder does not build a backlog: the SDK’s bounded image buffer discarded about 43% of the saturated input and returned 320.5 results/s with a median callback gap of 2.9 ms, while the Python-side queue stayed at two entries or fewer. For high-resolution cameras, cap CAP_PROP_FRAME_WIDTH / CAP_PROP_FRAME_HEIGHT or skip frames instead of pushing every captured frame.
Tested Environment
| Platform | Status | Evidence |
|---|---|---|
| Windows 11 (build 26200, AMD64) | Measured 2026-11-12 | Python 3.14.4, opencv-python 5.0.0.93 (cv2 5.0.0), numpy 2.5.4, dynamsoft-capture-vision-bundle 3.6.5000. USB camera via MSMF backend, 640 × 480, CAP_PROP_FPS = 30. Static decode, live camera and paced/saturated pipelines above. |
| Linux (x86_64 / aarch64) | Package and CI verified | 3.6.5000 publishes manylinux2014_x86_64 and manylinux_2_28_aarch64 wheels for CPython 3.10–3.14 (2026-10-29). The sample repo’s main.yml runs on ubuntu-latest with Python 3.12 and dynamsoft-capture-vision-bundle==3.6.5000 (CI run 41944834015, success). The camera pipeline was not re-run on a Linux desktop for this refresh. |
| macOS (Apple Silicon / Intel) | Package and demo verified | 3.6.5000 publishes macosx_12_0_universal2 wheels for CPython 3.10–3.14. The demo video above and the real-time screenshot in Step 2 were recorded on macOS for the original release; this refresh measured the Windows path. |
Version scope: dynamsoft-barcode-reader-bundle 11.6.5000 (used by the GitHub sample) and dynamsoft-capture-vision-bundle 3.6.5000 (used by this article) were both checked against PyPI and both decoded the 19-code sheet locally. opencv-python 5.0.0.93 is the current release (2026-07-02). Both Dynamsoft packages require a valid license; EnumErrorCode.EC_LICENSE_CACHE_USED (-20012) is a valid success code when a cached license is reused, so do not treat it as a failure.
Python Barcode Scanner Demo on macOS
Prerequisites
-
Dynamsoft Capture Vision Trial License: Get a 30-day free trial license for the Dynamsoft Capture Vision SDK.
-
Python Packages: Pin the versions used for the measurements above:
pip install dynamsoft-capture-vision-bundle==3.6.5000 opencv-pythonWhat are these packages for?
dynamsoft-capture-vision-bundleis the Dynamsoft Capture Vision SDK for Python. It providesLicenseManager,CaptureVisionRouter,ImageData,ImageSourceAdapterandCapturedResultReceiver.opencv-pythoncaptures camera frames and displays processed image results.- The GitHub sample pins the barcode-only alternative
dynamsoft-barcode-reader-bundle==11.6.5000; both packages expose the same API, so only the import line changes.
Python 3.10–3.14 are supported by the current wheels on Windows, Linux, and macOS.
Step 1: Decode Barcodes from an Image File
Since the Dynamsoft Capture Vision SDK is a unified framework integrated with various image processing tasks, we can easily switch between image processing modes by passing the PresetTemplate name to the capture() method.
Choose the Right Preset Template for Barcode Detection
The following code snippet shows the built-in PresetTemplate enumeration in the Dynamsoft Capture Vision SDK:
class EnumPresetTemplate(Enum):
PT_DEFAULT = _DynamsoftCaptureVisionRouter.getPT_DEFAULT()
PT_READ_BARCODES = _DynamsoftCaptureVisionRouter.getPT_READ_BARCODES()
PT_RECOGNIZE_TEXT_LINES = _DynamsoftCaptureVisionRouter.getPT_RECOGNIZE_TEXT_LINES()
PT_DETECT_DOCUMENT_BOUNDARIES = (
_DynamsoftCaptureVisionRouter.getPT_DETECT_DOCUMENT_BOUNDARIES()
)
PT_DETECT_AND_NORMALIZE_DOCUMENT = (
_DynamsoftCaptureVisionRouter.getPT_DETECT_AND_NORMALIZE_DOCUMENT()
)
PT_NORMALIZE_DOCUMENT = _DynamsoftCaptureVisionRouter.getPT_NORMALIZE_DOCUMENT()
PT_READ_BARCODES_SPEED_FIRST = (
_DynamsoftCaptureVisionRouter.getPT_READ_BARCODES_SPEED_FIRST()
)
PT_READ_BARCODES_READ_RATE_FIRST = (
_DynamsoftCaptureVisionRouter.getPT_READ_BARCODES_READ_RATE_FIRST()
)
PT_READ_SINGLE_BARCODE = _DynamsoftCaptureVisionRouter.getPT_READ_SINGLE_BARCODE()
PT_RECOGNIZE_NUMBERS = _DynamsoftCaptureVisionRouter.getPT_RECOGNIZE_NUMBERS()
PT_RECOGNIZE_LETTERS = _DynamsoftCaptureVisionRouter.getPT_RECOGNIZE_LETTERS()
PT_RECOGNIZE_NUMBERS_AND_LETTERS = (
_DynamsoftCaptureVisionRouter.getPT_RECOGNIZE_NUMBERS_AND_LETTERS()
)
PT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS = (
_DynamsoftCaptureVisionRouter.getPT_RECOGNIZE_NUMBERS_AND_UPPERCASE_LETTERS()
)
PT_RECOGNIZE_UPPERCASE_LETTERS = (
_DynamsoftCaptureVisionRouter.getPT_RECOGNIZE_UPPERCASE_LETTERS()
)
The PT_DEFAULT template supports multiple tasks, including document detection, MRZ recognition, and barcode detection. To optimize performance specifically for barcode detection, set the template to EnumPresetTemplate.PT_READ_BARCODES.value.
Decode Barcodes from an Image File
Referencing the previous document detection and MRZ recognition examples, the following code can be used to read barcodes from static images:
import sys
from dynamsoft_capture_vision_bundle import *
import os
import cv2
import numpy as np
from utils import *
if __name__ == '__main__':
print("**********************************************************")
print("Welcome to Dynamsoft Capture Vision - Barcode Sample")
print("**********************************************************")
error_code, error_message = LicenseManager.init_license(
"LICENSE-KEY")
if error_code != EnumErrorCode.EC_OK and error_code != EnumErrorCode.EC_LICENSE_CACHE_USED:
print("License initialization failed: ErrorCode:",
error_code, ", ErrorString:", error_message)
else:
cvr_instance = CaptureVisionRouter()
while (True):
image_path = input(
">> Input your image full path:\n"
">> 'Enter' for sample image or 'Q'/'q' to quit\n"
).strip('\'"')
if image_path.lower() == "q":
sys.exit(0)
if image_path == "":
image_path = "../../../images/multi.png"
if not os.path.exists(image_path):
print("The image path does not exist.")
continue
result = cvr_instance.capture(
image_path, EnumPresetTemplate.PT_READ_BARCODES.value)
if result.get_error_code() != EnumErrorCode.EC_OK:
print("Error:", result.get_error_code(),
result.get_error_string())
else:
cv_image = cv2.imread(image_path)
items = result.get_items()
print('Found {} barcodes.'.format(len(items)))
for item in items:
format_type = item.get_format_string()
text = item.get_text()
print("Barcode Format:", format_type)
print("Barcode Text:", text)
location = item.get_location()
x1 = location.points[0].x
y1 = location.points[0].y
x2 = location.points[1].x
y2 = location.points[1].y
x3 = location.points[2].x
y3 = location.points[2].y
x4 = location.points[3].x
y4 = location.points[3].y
del location
cv2.drawContours(
cv_image, [np.intp([(x1, y1), (x2, y2), (x3, y3), (x4, y4)])], 0, (0, 255, 0), 2)
cv2.putText(cv_image, text, (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
cv2.imshow(
"Original Image with Detected Barcodes", cv_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
input("Press Enter to quit...")
Note: Replace the
LICENSE-KEYwith your valid license key. The sample printsget_format_string()rather thanget_format(): in 3.6.5000 the latter returns the numeric format ID (for example2), while the former returnsCODE_128.
Running this script against images/multi.png returns 19 items in one capture() call. For PDFs and multi-page TIFFs, the sample’s file.py uses capture_multi_pages() and iterates get_results() instead — the bundled text-barcode.pdf returned 2 barcodes across 1 page in the same tested environment.
Test Multi-Barcode Detection from a Single Image
Decoding multiple barcodes from a single image is a common use case in retail and logistics. The following image contains multiple barcodes of different formats:

On dynamsoft-capture-vision-bundle 3.6.5000, this sheet produces 19 BarcodeResultItem objects from a single capture() call, with formats ranging from CODE_128 and EAN_13 through QR_CODE, PDF417, DATAMATRIX, AZTEC, MAXICODE and Micro QR.
Step 2: Decode Barcodes from a Live Webcam Stream
When reading barcodes from an image file, we invoke the capture() method in the main thread. However, for processing real-time video streams from a webcam, a different approach is needed to avoid blocking the main thread. The Dynamsoft Capture Vision SDK provides a built-in mechanism for handling real-time video frames and processing them asynchronously on a native C++ worker thread. To implement this, extend the ImageSourceAdapter and CapturedResultReceiver classes to handle the image data and captured results, respectively, then call the start_capturing() method to begin processing the video stream.
from dynamsoft_capture_vision_bundle import *
import cv2
import numpy as np
import queue
from utils import *
class FrameFetcher(ImageSourceAdapter):
def has_next_image_to_fetch(self) -> bool:
return True
def add_frame(self, imageData):
self.add_image_to_buffer(imageData)
class MyCapturedResultReceiver(CapturedResultReceiver):
def __init__(self, result_queue):
super().__init__()
self.result_queue = result_queue
def on_captured_result_received(self, captured_result):
self.result_queue.put(captured_result)
if __name__ == '__main__':
errorCode, errorMsg = LicenseManager.init_license(
"LICENSE-KEY")
if errorCode != EnumErrorCode.EC_OK and errorCode != EnumErrorCode.EC_LICENSE_CACHE_USED:
print("License initialization failed: ErrorCode:",
errorCode, ", ErrorString:", errorMsg)
else:
vc = cv2.VideoCapture(0)
if not vc.isOpened():
print("Error: Camera is not opened!")
exit(1)
cvr = CaptureVisionRouter()
fetcher = FrameFetcher()
cvr.set_input(fetcher)
# Create a thread-safe queue to store captured items
result_queue = queue.Queue()
receiver = MyCapturedResultReceiver(result_queue)
cvr.add_result_receiver(receiver)
errorCode, errorMsg = cvr.start_capturing(
EnumPresetTemplate.PT_READ_BARCODES.value)
if errorCode != EnumErrorCode.EC_OK:
print("error:", errorMsg)
while True:
ret, frame = vc.read()
if not ret:
print("Error: Cannot read frame!")
break
fetcher.add_frame(convertMat2ImageData(frame))
if not result_queue.empty():
captured_result = result_queue.get_nowait()
items = captured_result.get_items()
for item in items:
if item.get_type() == EnumCapturedResultItemType.CRIT_BARCODE:
text = item.get_text()
location = item.get_location()
x1 = location.points[0].x
y1 = location.points[0].y
x2 = location.points[1].x
y2 = location.points[1].y
x3 = location.points[2].x
y3 = location.points[2].y
x4 = location.points[3].x
y4 = location.points[3].y
cv2.drawContours(
frame, [np.intp([(x1, y1), (x2, y2), (x3, y3), (x4, y4)])], 0, (0, 255, 0), 2)
cv2.putText(frame, text, (x1, y1),
cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
del location
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cv2.imshow('frame', frame)
cvr.stop_capturing()
vc.release()
cv2.destroyAllWindows()
Explanation
- The
FrameFetcherclass implements theImageSourceAdapterinterface to feed frame data into the built-in buffer. - The
MyCapturedResultReceiverclass implements theCapturedResultReceiverinterface. Theon_captured_result_receivedmethod runs on a native C++ worker thread and sendsCapturedResultobjects to the main thread where they are stored in a thread-safe queue for further use. - A
CapturedResultcontains severalCapturedResultItemobjects. TheCRIT_BARCODEtype represents recognized barcode data. has_next_image_to_fetch()returnsTruefor the lifetime of the fetcher, so the worker keeps polling the buffer untilstop_capturing()is called.
Verify Real-Time Barcode Scanning on macOS

Step 3: Manage the Camera and Capture Lifecycle
The recognition code is short; most desktop bugs come from the order in which the camera, the native worker and the OpenCV windows are torn down.
| Order | Call | Why |
|---|---|---|
| 1 | LicenseManager.init_license(...) |
Accept both EC_OK and EC_LICENSE_CACHE_USED; the first activation needs network access. |
| 2 | vc.isOpened() check |
On Linux a missing /dev/video* node or missing video group membership silently fails here. |
| 3 | cvr.set_input(fetcher) → add_result_receiver(receiver) → start_capturing(...) |
Register both before starting, and check that start_capturing() returned EC_OK. |
| 4 | vc.read() → fetcher.add_frame(convertMat2ImageData(frame)) |
One ImageData per frame; the SDK buffer is bounded, so faster input does not queue forever. |
| 5 | result_queue.get_nowait() + cv2.imshow() |
Drain and draw in the main thread only. Never call OpenCV from the native receiver callback. |
| 6 | cv2.waitKey(1) |
Keeps the preview responsive and provides the q exit path. |
| 7 | cvr.stop_capturing() |
Stops the native worker before the camera device is released. |
| 8 | vc.release() → cv2.destroyAllWindows() |
Frees the camera and the windows; drain the queue once more afterwards. |
Three details matter in practice. First, on_captured_result_received() is a native thread callback: the safest implementation is self.result_queue.put(captured_result) and nothing else, because the CapturedResult and its items must stay referenced until the main thread reads them. Second, one result arrived after stop_capturing() in the 10-second camera run, so a final non-blocking drain avoids a stale overlay or a leaked object. Third, the sample’s del location releases the native location object after its four corner points have been copied; do not keep using location afterwards.
For a plain still-image path there is no worker thread and no shutdown sequence at all — CaptureVisionRouter.capture() is synchronous and returns its result in the calling thread.
Common Issues & Edge Cases
- Camera not detected on Linux: OpenCV’s
VideoCapture(0)may fail if the video device permissions are restricted. Runls /dev/video*to confirm the device exists and ensure your user has access (e.g., add to thevideogroup). On macOS, grant Camera access to the terminal or Python process in System Settings. - License initialization error: If
init_license()returns an error code other thanEC_OKorEC_LICENSE_CACHE_USED, verify that your license key is valid, has not expired, and that the machine has internet access for online activation. A 24-hour public trial key returns-10004(“24-hour Temporary license expired”) and cannot be reused once it lapses. - Slow decoding on high-resolution frames: If webcam frames are large (e.g., 4K), decoding latency increases. Resize frames before passing them to the SDK, or switch to
PT_READ_BARCODES_SPEED_FIRSTfor faster throughput at the cost of read rate. - First
capture()call is much slower: The first call in a fresh process initializes the engine — 138.0 ms versus a 77.6 ms median steady state onmulti.png. Warm up with one discarded call before timing anything. - Fewer result callbacks than submitted frames: Above roughly 320 decodes/s on a 640 × 480 sheet, the SDK’s bounded
ImageSourceAdapterbuffer drops frames instead of queueing them. In the saturated run, 5,640 submitted frames produced 3,206 callbacks. Throttle to the camera frame rate or skip frames; do not assume every submitted frame yields a callback. - Format printed as a number:
item.get_format()returns the integer format ID (2for CODE_128). Useitem.get_format_string()when you need a human-readable name. - BGR versus RGB confusion:
convertMat2ImageData()passes OpenCV’s BGR bytes withIPF_RGB_888. Both raw BGR bytes and RGB-corrected bytes returned the same 19 items onmulti.png, because barcode decoding uses luminance. For color-dependent tasks, convert withcv2.cvtColor(frame, cv2.COLOR_BGR2RGB)first. - Stale results or a frozen preview after
q:stop_capturing()must run beforevc.release(), and the receiver callback must never block on OpenCV calls. Keep thequeue.Queuenon-blocking (get_nowait()) and drain it once after shutdown.
Conclusion
OpenCV captures frames and draws results; CaptureVisionRouter.capture() decodes files in one call and start_capturing() with an ImageSourceAdapter decodes live frames asynchronously. The two paths share the same BarcodeResultItem fields, so a desktop scanner can support images, PDFs and a webcam without changing recognition logic — only the input source and the shutdown sequence differ.