Python scan code tool

As a tool of information transmission, TWO-DIMENSIONAL code plays an important role in today’s society. From mobile phone user login to mobile phone payment, the existence of QR code can be seen in every corner of life. Do you know how qr codes are interpreted? Have you ever thought of realizing a scanning code tool? Keep reading if you want to!

I. Case analysis

Let’s think about what we need to write to implement the scan code tool. In the process of scanning code, we need to open the camera, how to recognize the QR code by the phone or computer. So we need to implement two key steps: call the camera and recognize the QR code.

These operations correspond to two modules, namely OpencV, Intel’s computer vision processing module, and PyZbar, which is used to parse qr codes.

Second, the environment

Environments include Python environments and modules. My environment is as follows:

System: Windows10Python: python3.79.Opencv: opencv - python -4.4. 044.Pyzbar: pyzbar -0.18.
Copy the code

Install the opencV module as follows:

pip install opencv-python
Copy the code

Then there’s the PyZbar module:

pip install pyzbar
Copy the code

If no version is specified, the system automatically installs the latest version. After installing the module, we can implement the scanning code tool.

3. Identify the QR code

With the PyZbar module, our job of identifying qr codes is very simple. First, we need to prepare a QR code. With the TWO-DIMENSIONAL code, you can begin to parse, the specific steps are as follows:

  1. Read the two-dimensional code picture
  2. Parse the data in the QR code
  3. Extract data information from the parsed data

The implementation code is as follows:

import cv2
from pyzbar import pyzbar
# 1. Read the two-dimensional code picture
qrcode = cv2.imread('qrcode.jpg')
# 2. Parse the data in the QR code
data = pyzbar.decode(qrcode)
print(data)
# 3. Analyze the data information of two-dimensional code in the data
text = data[0].data.decode('utf-8')
print(text)
Copy the code

The first time we get a data, let’s look at what the data looks like:

[Decoded(data=b'http://weixin.qq.com/r/vC_fhynEKnRVrW3k93qu'.type='QRCODE', rect=Rect(left=140, top=113, width=390, height=390), polygon=[Point(x=140, y=113), Point(x=140, y=503), Point(x=530, y=503), Point(x=530, y=113)])]
Copy the code

You can see that it is a list, and the first data of the list contains the URL information. So we need to parse again with the following code:

text = data[0].data.decode('utf-8')
Copy the code

So we can get the information contained in the QR code. For future use, write the above code as a function:

def scan_qrcode(img_path) :
    qrcode = cv2.imread(img_path)
    data = pyzbar.decode(qrcode)
    return data[0].data.decode('utf-8')
Copy the code

Now let’s see how to call the camera.

Call the camera

Opencv provides a VideoCapture class for reading videos, which can also be used to call the camera. The steps to call the camera are as follows:

  1. Call the camera
  2. cycle
  3. Reads a frame in the loop
  4. Displays the screen being read
  5. Waiting for keyboard input
  6. Determine whether to press the exit key Q
  7. Press the push button to exit, not press to continue the cycle

The specific code is as follows:

import cv2
# Call the camera
cap = cv2.VideoCapture(0)
while True:
    # Read a frame
    ret, frame = cap.read()
    # Display current frame
    cv2.imshow('scan qrcode', frame)
    Wait for keyboard input
    key = cv2.waitKey(10)
    Turn off the camera when the q key is pressed
    if key == ord('q') :break
# Destroy all Windows
cv2.destroyAllWindows()
Copy the code

You can run the above code for yourself, and it will be like turning on your own front facing camera.

Now that the camera is called, we can combine the two pieces of code.

Five, the realization of scan code tools

The main part of our scanning tool is to call the operation of the camera. We need to parse every frame we read, and output and exit after parsing the result. The specific code is as follows:

import cv2
from pyzbar import pyzbar

def scan_qrcode(qrcode) :
    data = pyzbar.decode(qrcode)
    return data[0].data.decode('utf-8')

cap = cv2.VideoCapture(0)
while True:
    ret, frame = cap.read()
    cv2.imshow('scan qrcode', frame)

    # Parse qr code
    text = None
    try:
        text = scan_qrcode(frame)
    except Exception as e:
        pass
    if text:
        print(text)
        break

    key = cv2.waitKey(10)
    if key == ord('q') :break
cv2.destroyAllWindows()
Copy the code

We changed the scan_qrCode function from passing in the image path to passing in the image object directly. Because the image frames obtained by VideoCapture object and the image obtained by cv2.imread are of the same data type.

The key step above is the operation of parsing the QR code. First, define a text. Since an exception occurs if there are no qr codes during parsing, use the try-except statement. How to determine the content of the text by if, only when we really parse the data, the program will output the result, and exit the program.

At this point, we have implemented the scan code tool. Interested readers can follow my public account “new folder X”.