首页  >  文章  >  后端开发  >  如何构建适用于 Windows、Linux 和 macOS 的 Python 条码扫描器

如何构建适用于 Windows、Linux 和 macOS 的 Python 条码扫描器

DDD
DDD原创
2024-10-22 13:24:03762浏览

条形码扫描已成为从零售、物流到医疗保健等各个行业的必备工具。在桌面平台上,它可以快速捕获和处理信息,无需手动输入数据,从而节省时间并减少错误。在本教程中,我们将通过构建适用于 WindowsLinuxPython 条码扫描器,继续探索 Dynamsoft Capture Vision SDK 的功能和 macOS

macOS 上的 Python 条码扫描仪演示

先决条件

  • Dynamsoft Capture Vision 试用许可证:获取 Dynamsoft Capture Vision SDK 的 30 天试用许可证密钥。

  • Python 包:使用以下命令安装所需的 Python 包:

    pip install dynamsoft-capture-vision-bundle opencv-python
    

    这些包有什么用?

    • dynamsoft-capture-vision-bundle 是适用于 Python 的 Dynamsoft Capture Vision SDK。
    • opencv-python 捕获相机帧并显示处理后的图像结果。

从静态图像中读取条形码

由于 Dynamsoft Capture Vision SDK 是一个集成了各种图像处理任务的统一框架,因此我们可以通过将 PresetTemplate 名称传递给 capture() 方法来轻松切换图像处理模式。

Dynamsoft Capture Vision SDK 内置模板

以下代码片段显示了 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 模板支持多种任务,包括文档检测、机读区识别和条形码检测。要专门优化条形码检测的性能,请将模板设置为 EnumPresetTemplate.PT_READ_BARCODES.value。

用于条形码检测的Python代码

参考之前的文档检测和机读区识别示例,可以使用以下代码从静态图像中读取条形码:

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 替换为您的有效许可证密钥。

使用多条形码图像测试 Python 条形码阅读器

从单个图像中解码多个条形码是零售和物流中的常见用例。下图包含多个不同格式的条形码:

How to Build a Python Barcode Scanner for Windows, Linux, and macOS

使用网络摄像头进行实时多条形码检测

当从图像文件中读取条形码时,我们在主线程中调用 capture() 方法。然而,为了处理来自网络摄像头的实时视频流,需要采用不同的方法来避免阻塞主线程。 Dynamsoft Capture Vision SDK 提供了一种内置机制,用于处理实时视频帧并在本机 C 工作线程上异步处理它们。要实现此目的,请扩展 ImageSourceAdapter 和 CapturedResultReceiver 类来分别处理图像数据和捕获的结果,然后调用 start_capturing() 方法开始处理视频流。

pip install dynamsoft-capture-vision-bundle opencv-python

说明

  • FrameFetcher 类实现 ImageSourceAdapter 接口,将帧数据送入内置缓冲区。
  • MyCapturedResultReceiver 类实现了 CapturedResultReceiver 接口。 on_captured_result_received 方法在本机 C 工作线程上运行,并将 CapturedResult 对象发送到主线程,并将它们存储在线程安全队列中以供进一步使用。
  • CapturedResult 包含多个 CapturedResultItem 对象。 CRIT_BARCODE 类型表示已识别的条形码数据。

在 macOS 上测试 Python 条形码扫描仪

How to Build a Python Barcode Scanner for Windows, Linux, and macOS

源代码

https://github.com/yushulx/python-barcode-qrcode-sdk/tree/main/examples/official/10.x

以上是如何构建适用于 Windows、Linux 和 macOS 的 Python 条码扫描器的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn