资讯详情

Python+pyzbar识别二维码条形码

前言 如何是使用 pyzbar 快速识别二维码和条形码

一、pyzbar 是什么? 首先需要了解 ZBar:ZBar它是从各种来源(如视频流、图像文件和原始强度传感器)读取条形码的开源软件套件。它支持包括在内的许多流行符号(条形码类型)EAN-13/UPC-A、UPC-E、EAN-8.代码128,代码39,交错2/5和二维码。

而 pyzbar 是通过 Python2、3接口,使用 ZBar 库读取一维条形码和QR码 。 二、安装 pyzbar

  1. Windows 在 Windows 只需在环境中使用 pip 安装即可:

    pip install pyzbar

三、开始识别

 import datetime import time from pathlib import Path import numpy as np import cv2 from pyzbar import pyzbar   def get_qrcode_result(image_input, binary_max=230, binary_step=2):     """ 获取二维码的结果 :param image_input: 输入图片数据 :param binary_max: 二值化最大值 :param binary_step: 每次增加的二值化步长 :return: pyzbar 预测的结果 """     # 灰度化输入图像     if len(image_input.shape) >= 3:         image_input = cv2.cvtColor(image_input, cv2.COLOR_RGB2GRAY)    # 转换灰度图      # 获取自适配阈值     binary, _ = cv2.threshold(image_input, 0, 255, cv2.THRESH_OTSU)      # 二值化递增检测     res = []     while (binary < binary_max) and (len(res) == 0):         binary, mat = cv2.threshold(image, binary, 255, cv2.THRESH_BINARY)         res = pyzbar.decode(mat)         binary  = binary_step      return res   if __name__ == '__main__':      image_dir = Path(r"图片路径")     total_image = 0
    success_count = 0
    for image_file in Path.iterdir(image_dir):
        if image_file.suffix not in [".jpg", ".png"]:
            # 非图片,跳过该文件
            continue

        # 使用 cv2.imdecode 可以读取中文路径下的图片
        image = cv2.imdecode(np.fromfile(Path(image_dir).joinpath(image_file), 
                                         dtype=np.uint8), 
                             cv2.IMREAD_COLOR)

        start_time = time.time()
        result = get_qrcode_result(image, binary_max=230, binary_step=2)

        print(f"Got { 
         image_file} result: { 
         result}, "
              f"using time : { 
         datetime.timedelta(seconds=(time.time() - start_time))}")

        if len(result) > 0:
            success_count += 1
        total_image += 1

    print(f"total image = { 
         total_image}, success count = { 
         success_count}")

在这里插入图片描述

可能出现的问题: 安装完,run,出现如下报错! FileNotFoundError: Could not find module ‘你的路径\Python\Python38\site-packages\pyzbar\libzbar-64.dll’ (or one of its dependencies). Try using the full path with constructor syntax.

解决方法: 没事,这个坑我已经踩过。这个报错的原因是没有安装 Visual C++ 的依赖库

下载地址:Visual C++ Redistributable Packages for Visual Studio 2013

进入之后,拉到下面可以看到下载的按钮,下载完之后安装即可!:

参考: [1] pyzbar 安装 [2] OSError: [WinError 126] Cannot find the specified module.

标签: 传感器条码

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

锐单商城 - 一站式电子元器件采购平台