搜索
首页后端开发Python教程如何构建适用于 Windows、Linux 和 macOS 的 Python 条码扫描器

条形码扫描已成为从零售、物流到医疗保健等各个行业的必备工具。在桌面平台上,它可以快速捕获和处理信息,无需手动输入数据,从而节省时间并减少错误。在本教程中,我们将通过构建适用于 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
了解差异:用于循环和python中的循环了解差异:用于循环和python中的循环May 16, 2025 am 12:17 AM

theDifferenceBetweewneaforoopandawhileLoopInpythonisthataThataThataThataThataThataThataNumberoFiterationSiskNownInAdvance,而leleawhileLoopisusedWhenaconDitionNeedneedneedneedNeedStobeCheckedStobeCheckedStobeCheckedStobeCheckedStobeceDrepeTysepectients.peatsiveSectlyStheStobeCeptellyWithnumberofiterations.1)forloopsareAceareIdealForitoringercortersence

Python循环控制:对于vs -a -a比较Python循环控制:对于vs -a -a比较May 16, 2025 am 12:16 AM

在Python中,for循环适用于已知迭代次数的情况,而while循环适合未知迭代次数且需要更多控制的情况。1)for循环适用于遍历序列,如列表、字符串等,代码简洁且Pythonic。2)while循环在需要根据条件控制循环或等待用户输入时更合适,但需注意避免无限循环。3)性能上,for循环略快,但差异通常不大。选择合适的循环类型可以提高代码的效率和可读性。

如何在Python中结合两个列表:5种简单的方法如何在Python中结合两个列表:5种简单的方法May 16, 2025 am 12:16 AM

在Python中,可以通过五种方法合并列表:1)使用 运算符,简单直观,适用于小列表;2)使用extend()方法,直接修改原列表,适用于需要频繁更新的列表;3)使用列表解析式,简洁且可对元素进行操作;4)使用itertools.chain()函数,内存高效,适合大数据集;5)使用*运算符和zip()函数,适用于需要配对元素的场景。每种方法都有其特定用途和优缺点,选择时应考虑项目需求和性能。

循环时循环:python语法,用例和示例循环时循环:python语法,用例和示例May 16, 2025 am 12:14 AM

foroopsare whenthenemberofiterationsisknown,而whileLoopsareUseduntilacTitionismet.1)ForloopSareIdealForeSequencesLikeLists,UsingSyntaxLike'forfruitinFruitinFruitinFruitIts:print(fruit)'。2)'

python串联列表列表python串联列表列表May 16, 2025 am 12:08 AM

toConcateNateAlistofListsInpython,useextend,listComprehensions,itertools.Chain,orrecursiveFunctions.1)ExtendMethodStraightForwardButverBose.2)listComprechencomprechensionsareconconconciseandemandeconeandefforlargerdatasets.3)

Python中的合并列表:选择正确的方法Python中的合并列表:选择正确的方法May 14, 2025 am 12:11 AM

Tomergelistsinpython,YouCanusethe操作员,estextMethod,ListComprehension,Oritertools

如何在Python 3中加入两个列表?如何在Python 3中加入两个列表?May 14, 2025 am 12:09 AM

在Python3中,可以通过多种方法连接两个列表:1)使用 运算符,适用于小列表,但对大列表效率低;2)使用extend方法,适用于大列表,内存效率高,但会修改原列表;3)使用*运算符,适用于合并多个列表,不修改原列表;4)使用itertools.chain,适用于大数据集,内存效率高。

Python串联列表字符串Python串联列表字符串May 14, 2025 am 12:08 AM

使用join()方法是Python中从列表连接字符串最有效的方法。1)使用join()方法高效且易读。2)循环使用 运算符对大列表效率低。3)列表推导式与join()结合适用于需要转换的场景。4)reduce()方法适用于其他类型归约,但对字符串连接效率低。完整句子结束。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)