基於opencv4.0 pyzbar和python實現二維碼實時檢測+定位

基於opencv4.0 pyzbar和python實現二維碼實時檢測+定位

1.寫在前面

opencv4.0終於發佈了,以後應該視覺的項目都是基於opencv4.0版本的,所以現在也是升級到4.0版本,具體和3.0版本的區別很小,具體可以查看這裏

2.前期準備

opencv 4.0(3.0)

python 3.8

pyzbar

3.效果演示

如果二維碼是中文utf-8字符的話無法利用opencv在圖像上顯示出來,有需要的童鞋可以使用matplotlib顯示圖像。

4.實現目標

利用攝像頭完成了實時對二維碼的識別和檢測、定位,獲取二維碼的中心點與外接最小矩形。

5.代碼

import cv2
from pyzbar import pyzbar
#二維碼動態識別
camera=cv2.VideoCapture(0)
camera.set(3,1280) #設置分辨率
camera.set(4,768)
while True:
    (grabbed,frame)=camera.read()
    #獲取畫面中心點
    h1,w1= frame.shape[0],frame.shape[1]

    # 糾正畸變(這裏把相機標定的代碼去除了,各位自行標定吧)
    dst = frame

    # 掃描二維碼
    text = pyzbar.decode(dst)
    for texts in text:
        textdate = texts.data.decode('utf-8')
        print(textdate)
        (x, y, w, h) = texts.rect#獲取二維碼的外接矩形頂點座標
        print('識別內容:'+textdate)

        # 二維碼中心座標
        cx = int(x + w / 2)
        cy = int(y + h / 2)
        cv2.circle(dst, (cx, cy), 2, (0, 255, 0), 8)  # 做出中心座標
        print('中間點座標:',cx,cy)
        coordinate=(cx,cy)
        #在畫面左上角寫出二維碼中心位置
        cv2.putText(dst,'QRcode_location'+str(coordinate),(20,20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
        #畫出畫面中心與二維碼中心的連接線
        cv2.line(dst, (cx,cy),(int(w1/2),int(h1/2)), (255, 0, 0), 2)
        #cv2.rectangle(dst, (x, y), (x + w, y + h), (0, 255, 255), 2)  # 做出外接矩形
        #二維碼最小矩形
        cv2.line(dst, texts.polygon[0], texts.polygon[1], (255, 0, 0), 2)
        cv2.line(dst, texts.polygon[1], texts.polygon[2], (255, 0, 0), 2)
        cv2.line(dst, texts.polygon[2], texts.polygon[3], (255, 0, 0), 2)
        cv2.line(dst, texts.polygon[3], texts.polygon[0], (255, 0, 0), 2)
        #寫出掃描內容
        txt = '(' + texts.type + ')  ' + textdate
        cv2.putText(dst, txt, (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 50, 255), 2)


    cv2.imshow('dst',dst)
    if cv2.waitKey(1) & 0xFF == ord('q'):  # 按q保存一張圖片
        cv2.imwrite("./frame.jpg", frame)
        break

camera.release()
cv2.destroyAllWindows()

代碼直接運行就行,適用於opencv3.x和4.x版本

6.後記

這個項目是用於實現一個機器人利用視覺和二維碼標籤進行定位的,現在實現了初步的簡單功能

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章