条形码扫描已成为从零售、物流到医疗保健等各个行业的重要工具。在桌面平台上,它可以快速捕获和处理信息,无需手动输入数据,从而节省时间并减少错误。在本教程中,我们将通过构建适用于 Windows、Linux 的 Python 条形码扫描仪 继续探索 Dynamsoft Capture Vision SDK 的功能和 macOS。
Dynamsoft Capture Vision 试用许可证:获取 Dynamsoft Capture Vision SDK 的 30 天试用许可证密钥。
Python 包:使用以下命令安装所需的 Python 包:
pip install dynamsoft-capture-vision-bundle opencv-python
这些包有什么用?
由于Dynamsoft Capture Vision SDK是一个集成了各种图像处理任务的统一框架,我们可以通过将PresetTemplate名称传递给capture()方法来轻松切换图像处理模式。
以下代码片段显示了 Dynamsoft Capture Vision SDK 中内置的 PresetTemplate 枚举:
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() )
PT_DEFAULT 模板支持多种任务,包括文档检测、MRZ 识别和条形码检测。要专门优化条形码检测的性能,请将模板设置为 EnumPresetTemplate.PT_READ_BARCODES.value。
参考之前的文档检测和机读区识别示例,可以使用以下代码从静态图像中读取条形码:
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() 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...")
注意:将 LICENSE-KEY 替换为您的有效许可证密钥。
从单个图像中解码多个条形码是零售和物流中的常见用例。下图包含多个不同格式的条形码:
当从图像文件中读取条形码时,我们在主线程中调用 capture() 方法。然而,为了处理来自网络摄像头的实时视频流,需要采用不同的方法来避免阻塞主线程。 Dynamsoft Capture Vision SDK 提供了一种内置机制,用于处理实时视频帧并在本机 C 工作线程上异步处理它们。要实现此目的,请扩展 ImageSourceAdapter 和 CapturedResultReceiver 类来分别处理图像数据和捕获的结果,然后调用 start_capturing() 方法开始处理视频流。
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()
解释
https://github.com/yushulx/python-barcode-qrcode-sdk/tree/main/examples/official/10.x
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3