Python implements scanning tools

Python implements scan code tool##

As a tool of information transmission, QR code has played an important role in today's society. From mobile phone users logging in to mobile payment, QR codes can be seen in every corner of life. Do you know how the QR code is parsed? Have you ever thought about implementing a code scanning tool yourself? Keep reading if you want!

One, case analysis##

Let us first think about what operations need to be written to realize the scanning tool. In the process of scanning the code, we need to open the camera, how to recognize the QR code from the mobile phone or computer. So we have to implement two key steps: call the camera and identify the QR code.

These two operations correspond to two modules respectively, they are opencv and pyzbar, where opencv is Intel's computer vision processing module, and pyzbar is a module used to parse QR codes.

2. Environment##

The environment includes python environment and modules. My environment is as follows:

System: Windows 10
python:python 3.7.9
opencv:opencv-python-4.4.0.44
pyzbar:pyzbar-0.1.8

Module installation is very simple, we install directly with pip, first install the opencv module:

pip install opencv-python

Then the pyzbar module:

pip install pyzbar

When the installation version is not specified, the system will automatically install the latest version. After installing the module, we can implement the code scanning tool.

Three, identify the QR code##

With the pyzbar module, our job of identifying the QR code is very simple. First, we need to prepare a QR code. Once you have the QR code, you can start parsing. The specific steps are as follows:

  1. Read the QR code picture 2. Analyze the data in the QR code 3. Extract the data information from the parsed data

The implementation code is as follows:

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

We parsed the above twice, and got a data for the first time. Let's take a 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)])]

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

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

So we can get the information contained in the QR code. In order to facilitate subsequent use, the above code can be written as a function:

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

Next we will look at how to call the camera.

Fourth, call the camera##

A VideoCapture class is provided in opencv to read the video, which can also be used to call the camera. The steps to call the camera are as follows:

  1. Call the camera 2. Loop 3. Read a frame in the loop 4. Display the currently read screen 5. Wait for keyboard input 6. Judge whether to press the exit key q7. Press the exit key to exit, if not press it to continue the cycle

The specific code is as follows:

import cv2
# Call camera
cap = cv2.VideoCapture(0)while True:
 # Read a frame
 ret, frame = cap.read()
 # Show current frame
 cv2.imshow('scan qrcode', frame)
 # Waiting 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()

You can try to run the above code yourself, the effect is like turning on your front camera.

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

Five, realize the scanning tool##

The main part of our code scanning tool is the operation of calling the camera. We need to parse each frame we read, and output and exit when the result is parsed. 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)

 # Analyze the 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()

We modified the scan_qrcode function above, from the original path of the incoming image to the direct incoming image object. Because the picture frame obtained through the VideoCapture object and the picture obtained through cv2.imread are of the same data type.

The key step above is to analyze the operation of the QR code. First define a text, because an exception will occur if there is no QR code during the parsing process, so use the try-except statement to handle it. How to judge the content of 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 realized the scanning tool.

Recommended Posts

Python implements scanning tools
Python implements Super Mario
Python implements tic-tac-toe game
Python implements tic-tac-toe game
Python implements Tetris game
Python implements image stitching
Python implements minesweeper game
Python implements threshold regression
Python implements minesweeper games
Python implements electronic dictionary
Python implements guessing game
Python implements simple tank battle
Python implements udp chat window
Python implements WeChat airplane game
Python implements word guessing game
Python implements a guessing game
Python implements parking management system
Python implements digital bomb game
Python implements TCP file transfer
Python numpy implements rolling case
OpenCV Python implements puzzle games
Python implements simple tic-tac-toe game
Python implements password strength verification
Python implements car management system
Python multi-threaded port scanning tool
Python implements panoramic image stitching
Python implements SMTP mail sending
Python implements multi-dimensional array sorting
How Python implements FTP function
Python implements mean-shift clustering algorithm
Python implements verification code recognition
Python implements gradient descent method
Python implements text version minesweeper
Python implements image stitching function
Python implements the brick-and-mortar game
Python implements student performance evaluation system
How Python implements the mail function
Python simply implements the snake game
Python3 implements the singleton design pattern
Python implements exchange rate conversion operations
Python implements string and number splicing
Python implements ten classic sorting algorithms
Python implements a universal web framework
Python implements 126 mailboxes to send mail
Introduce several Python performance optimization tools
Python implements AI face change function
Python implements the steepest descent method
Python implements the actual banking system
Python implements digital bomb game program
Python implements ftp file transfer function
Python implements username and password verification
How Python implements the timer function
Python implements the aircraft war project
Python implements horizontal stitching of pictures
Python implements GIF graph upside down
Python implements QQ mailbox to send mail
Python implements alternate execution of two threads
Python implements the sum of fractional sequences
python implements the gradient method python the fastest descent method
Python implements singly linked lists and dictionaries
python3 simply implements the combined design pattern