欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

OpenCV和Pyzbar檢測(cè)二維碼和條碼

 更新時(shí)間:2024年11月03日 08:27:00   作者:燕鵬01  
在現(xiàn)代社會(huì),二維碼和條碼的應(yīng)用非常廣泛,從商品標(biāo)簽到支付二維碼,本文將詳細(xì)介紹如何使用?OpenCV?和?Pyzbar?庫在?Python?中檢測(cè)并識(shí)別二維碼和條碼,需要的可以參考下

概述

在現(xiàn)代社會(huì),二維碼和條碼的應(yīng)用非常廣泛,從商品標(biāo)簽到支付二維碼,幾乎無處不在。本文將詳細(xì)介紹如何使用 OpenCV 和 Pyzbar 庫在 Python 中檢測(cè)并識(shí)別二維碼和條碼,并通過具體的代碼示例來展示整個(gè)過程。

環(huán)境準(zhǔn)備

在開始之前,請(qǐng)確保已經(jīng)安裝了所需的庫??梢酝ㄟ^以下命令進(jìn)行安裝:

pip install opencv-python pyzbar

完整示例代碼詳解

import cv2
import numpy as np
from pyzbar import pyzbar

class CodeFinder:
    """
    二維碼、條碼檢測(cè)
    """
    def __init__(self):
        """
        初始化攝像頭并設(shè)置分辨率
        """
        self.cap = cv2.VideoCapture(0)  # 打開默認(rèn)攝像頭
        self.cap.set(3, 640)  # 設(shè)置視頻寬度為640像素
        self.cap.set(4, 480)  # 設(shè)置視頻高度為480像素

    def run(self):
        """
        捕獲視頻并檢測(cè)二維碼和條碼
        """
        while True:
            success, img = self.cap.read()  # 讀取一幀視頻
            if not success:
                print("Failed to read frame")
                break

            # 檢測(cè)圖像中的二維碼和條碼
            for bar_code in pyzbar.decode(img):
                # 解碼二維碼數(shù)據(jù)
                print(bar_code.data.decode('utf8'))  # 打印二維碼數(shù)據(jù)
                print(bar_code.type)  # 打印二維碼類型
                print(bar_code.rect)  # 打印二維碼四周邊界(矩形框)
                print(bar_code.polygon)  # 打印二維碼多邊形邊框
                print(bar_code.quality)  # 打印二維碼質(zhì)量
                print(bar_code.orientation)  # 打印二維碼方向

                # 繪制二維碼邊界
                points = np.array(bar_code.polygon, np.int32)
                points = points.reshape((-1, 1, 2))
                cv2.polylines(img=img, pts=[points], isClosed=True, color=(0, 0, 255), thickness=3)

                # 在圖像上顯示二維碼數(shù)據(jù)
                cv2.putText(
                    img=img,
                    text=bar_code.data.decode('utf8'),
                    org=(bar_code.rect.left, bar_code.rect.top),
                    fontFace=cv2.FONT_HERSHEY_SIMPLEX,
                    fontScale=0.8,
                    color=(0, 0, 255),
                    thickness=2
                )

            # 顯示圖像
            cv2.imshow('code', img)

            # 按下 'q' 鍵退出循環(huán)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                self.cap.release()  # 釋放攝像頭資源
                cv2.destroyAllWindows()  # 關(guān)閉所有OpenCV窗口
                break

if __name__ == '__main__':
    code_finder = CodeFinder()
    code_finder.run()

代碼解析

1. 導(dǎo)入必要的庫

import cv2
import numpy as np
from pyzbar import pyzbar
  • cv2:OpenCV 的 Python 接口,用于圖像和視頻處理。
  • numpy:用于處理圖像數(shù)據(jù)的數(shù)組。
  • pyzbar:用于解碼二維碼和條碼的庫。

2. 定義 CodeFinder 類

class CodeFinder:
    """
    二維碼、條碼檢測(cè)
    """
    def __init__(self):
        """
        初始化攝像頭并設(shè)置分辨率
        """
        self.cap = cv2.VideoCapture(0)  # 打開默認(rèn)攝像頭
        self.cap.set(3, 640)  # 設(shè)置視頻寬度為640像素
        self.cap.set(4, 480)  # 設(shè)置視頻高度為480像素

初始化攝像頭:

self.cap = cv2.VideoCapture(0):打開默認(rèn)攝像頭(ID 為 0)。

self.cap.set(3, 640):設(shè)置視頻寬度為 640 像素。

self.cap.set(4, 480):設(shè)置視頻高度為 480 像素。

3. 定義 run 方法

def run(self):
    """
    捕獲視頻并檢測(cè)二維碼和條碼
    """
    while True:
        success, img = self.cap.read()  # 讀取一幀視頻
        if not success:
            print("Failed to read frame")
            break

        # 檢測(cè)圖像中的二維碼和條碼
        for bar_code in pyzbar.decode(img):
            # 解碼二維碼數(shù)據(jù)
            print(bar_code.data.decode('utf8'))  # 打印二維碼數(shù)據(jù)
            print(bar_code.type)  # 打印二維碼類型
            print(bar_code.rect)  # 打印二維碼四周邊界(矩形框)
            print(bar_code.polygon)  # 打印二維碼多邊形邊框
            print(bar_code.quality)  # 打印二維碼質(zhì)量
            print(bar_code.orientation)  # 打印二維碼方向

            # 繪制二維碼邊界
            points = np.array(bar_code.polygon, np.int32)
            points = points.reshape((-1, 1, 2))
            cv2.polylines(img=img, pts=[points], isClosed=True, color=(0, 0, 255), thickness=3)

            # 在圖像上顯示二維碼數(shù)據(jù)
            cv2.putText(
                img=img,
                text=bar_code.data.decode('utf8'),
                org=(bar_code.rect.left, bar_code.rect.top),
                fontFace=cv2.FONT_HERSHEY_SIMPLEX,
                fontScale=0.8,
                color=(0, 0, 255),
                thickness=2
            )

        # 顯示圖像
        cv2.imshow('code', img)

        # 按下 'q' 鍵退出循環(huán)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            self.cap.release()  # 釋放攝像頭資源
            cv2.destroyAllWindows()  # 關(guān)閉所有OpenCV窗口
            break

讀取視頻幀:

success, img = self.cap.read():讀取一幀視頻。success 表示是否成功讀取,img 是讀取到的圖像。

如果讀取失敗,打印錯(cuò)誤信息并退出循環(huán)。

檢測(cè)二維碼和條碼:

  • for bar_code in pyzbar.decode(img):使用 pyzbar.decode() 函數(shù)檢測(cè)圖像中的二維碼和條碼。
  • print(bar_code.data.decode('utf8')):打印二維碼數(shù)據(jù)。
  • print(bar_code.type):打印二維碼類型。
  • print(bar_code.rect):打印二維碼四周邊界(矩形框)。
  • print(bar_code.polygon):打印二維碼多邊形邊框。
  • print(bar_code.quality):打印二維碼質(zhì)量。
  • print(bar_code.orientation):打印二維碼方向。

繪制二維碼邊界:

points = np.array(bar_code.polygon, np.int32):將二維碼多邊形邊框轉(zhuǎn)換為 NumPy 數(shù)組。

points = points.reshape((-1, 1, 2)):重塑數(shù)組形狀。

cv2.polylines(img=img, pts=[points], isClosed=True, color=(0, 0, 255), thickness=3):使用 cv2.polylines() 函數(shù)繪制多邊形邊框。

在圖像上顯示二維碼數(shù)據(jù):

cv2.putText():在圖像上顯示二維碼數(shù)據(jù)。

text=bar_code.data.decode('utf8'):要顯示的文本內(nèi)容。

org=(bar_code.rect.left, bar_code.rect.top):文本的起始位置。

fontFace=cv2.FONT_HERSHEY_SIMPLEX:使用的字體類型。

fontScale=0.8:字體大小。

color=(0, 0, 255):文本顏色。

thickness=2:文本線寬。

顯示圖像:

cv2.imshow('code', img):顯示圖像。

按鍵檢測(cè):

if cv2.waitKey(1) & 0xFF == ord('q'):等待1毫秒,如果有按鍵按下,返回按鍵的ASCII碼。ord('q') 返回字符 ‘q’ 的ASCII碼。如果按鍵為 ‘q’,則退出循環(huán)。

self.cap.release():釋放攝像頭資源。

cv2.destroyAllWindows():關(guān)閉所有OpenCV窗口。

4. 主函數(shù)

if __name__ == '__main__':
    code_finder = CodeFinder()
    code_finder.run()

主函數(shù):

if __name__ == '__main__'::確保當(dāng)腳本直接運(yùn)行時(shí)才執(zhí)行以下代碼。

創(chuàng)建 CodeFinder 對(duì)象并調(diào)用 run 方法來啟動(dòng)二維碼和條碼檢測(cè)。

總結(jié)

本文詳細(xì)介紹了如何使用 OpenCV 和 Pyzbar 庫在 Python 中檢測(cè)并識(shí)別二維碼和條碼,并通過具體的代碼示例展示了整個(gè)過程。通過使用 cv2.VideoCapture()、pyzbar.decode()、cv2.polylines() 和 cv2.putText() 等函數(shù),我們可以輕松地處理視頻流中的二維碼和條碼數(shù)據(jù)。

到此這篇關(guān)于OpenCV和Pyzbar檢測(cè)二維碼和條碼的文章就介紹到這了,更多相關(guān)OpenCV Pyzbar檢測(cè)二維碼和條碼內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論