QR code and barcode recognition based on OpenCV

hello

Today we will learn to use OpenCV to recognize QR codes and barcodes. First, we need to prepare a QR code. I will prepare two

Next we need to download several packages, numpy, opencv, and pyzbar (this toolkit can recognize QR codes, barcodes, etc.)

import cv2
import  numpy as  np
from  pyzbar.pyzbar import  decode

img = cv2.imread('Like.png')
code = decode(img)
print(code)


You can get the information of the QR code and his, four vertices and other information.

In the next step, we use the camera to identify

import cv2
import  numpy as  np
from  pyzbar.pyzbar import  decode

#img = cv2.imread('Like.png')
cap = cv2.VideoCapture(0)
cap.set(3,640)
cap.set(4,480)

while True:
    success,img =cap.read()
    for barcode in decode(img):
        print(barcode.data)
        myData = barcode.data.decode('utf-8')
        print(myData)


    cv2.imshow("Result",img)
    cv2.waitKey(1)

After this step, the QR code can be recognized in real time. Next we add a box to the recognized QR code:

    for barcode in decode(img):
        print(barcode.data)
        #添加方框
        pts = np.array([barcode.polygon],np.int32)
        pts = pts.reshape((-1,1,2))
        cv2.polylines(img,[pts],True,(255,15,255),5)
        
        myData = barcode.data.decode('utf-8')
        print(myData)

 Realization effect:

 Then add the recognized text to the QR code:

        #添加文本
        pts2 = barcode.rect
        cv2.putText(img,myData,(pts2[0],pts2[1]),cv2.FONT_HERSHEY_SIMPLEX,0.9,(255,50,255),2)

Renderings:

 This function has been implemented here. Of course, we can further expand it and make it an identity recognition tool. The effect is as follows:

 Complete code:

import cv2
import  numpy as  np
from  pyzbar.pyzbar import  decode

#img = cv2.imread('Like.png')
cap = cv2.VideoCapture(0)
cap.set(3,640)
cap.set(4,480)

with open('myDataID.text') as f:
    myDatalist = f.read().splitlines()



while True:
    success,img =cap.read()
    for barcode in decode(img):
        myData = barcode.data.decode('utf-8')
        print(myData)
        if myData in myDatalist:
            myOutPut = 'Authorization'
            myColour = (0,255,0)
        else:
            myOutPut = 'Un-Authorization'
            myColour = (0,0,255)

        #添加方框
        pts = np.array([barcode.polygon],np.int32)
        pts = pts.reshape((-1,1,2))
        cv2.polylines(img,[pts],True,myColour,5)

        #添加文本
        pts2 = barcode.rect
        cv2.putText(img,myOutPut,(pts2[0],pts2[1]),cv2.FONT_HERSHEY_SIMPLEX,0.9,myColour,2)


    cv2.imshow("Result",img)
    cv2.waitKey(1)

 goodbye

Guess you like

Origin blog.csdn.net/qq_41059950/article/details/123019955