Use the Flask framework to quickly deploy the HyperLPR license plate recognition API interface

overview

The license plate number can be quickly read through the open source library HyperLPR. For convenience, we can package the Python script into a WEBAPI interface and implement it with lightweight Flask to facilitate the docking and use of third-party applications.
Main implementation: Upload a photo containing the license plate number through the API interface, and the API interface will give the license plate recognition result. At the same time, it provides a picture online viewing URL, and marks the license plate.
HyperLPR official address: https://github.com/zeusees/HyperLPR

Install library environment

Install Anaconda

Anaconda is a commonly used python package management program, which can set up multiple python environments.
Download the Anaconda installation script

wget https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/Anaconda3-2021.05-Linux-x86_64.sh --no-check-certificate

After the download is complete, execute the installation, you will be prompted to read the authorization, just press Enter all the time

sh Anaconda3-2021.05-Linux-x86_64.sh

Then prompt you whether you agree, enter yes,
you will be asked about the installation location during the installation process, generally you don’t need to change it, just press Enter, it will automatically decompress
Finally, you will be prompted whether to initialize some configurations of Anaconda, remember to enter yes

After installation, configure Anaconda to the environment variable, and you can use the shortcut conda command

vim ~/.bashrc #编辑环境配置文件
export PATH="~/anaconda3/bin:$PATH" # 在第一行加入这个

Enter i in vim to edit, press Esc after editing, and then enter: wq to save the modification

After saving, update the environment variable and enter on the command line:

source ~/.bash_profile

Finally, verify whether the configuration is successful. If it is not saved, the configuration is successful!

After installation, create a python3.8 environment, execute the command, there will be a confirmation, enter y, and then press Enter

conda create --name hyperlpr_env python=3.8 --channel https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free/

Activate the hyperlpr_env environment

conda activate hyperlpr_env

Install Hyperlpr and Flask

#更新pip源
pip3 install --upgrade pip -i https://pypi.tuna.tsinghua.edu.cn/simple
#安装HyperLPR
pip3 install hyperlpr -i https://pypi.tuna.tsinghua.edu.cn/simple
#安装HyperLPR指定的opencv版本
pip3 install opencv-python==3.4.9.31 -i https://pypi.tuna.tsinghua.edu.cn/simple
#安装flask框架用于搭建WebApi接口
pip3 install flask -i https://pypi.tuna.tsinghua.edu.cn/simple
#安装requests用于测试接口请求
pip3 install requests  -i https://pypi.tuna.tsinghua.edu.cn/simple

Deploy Python script code

import base64
import flask
import json
import cv2
import numpy as np
from flask import Flask, request, make_response
from hyperlpr import *

sever = Flask(__name__)

@sever.route("/hyperlpr_file.do", methods=["post"])
def upload():
    # 上传文件,取一个名字,再给名字一个默认值None
    f = flask.request.files.get('file', None)
    if f:
        # 如果文件不为空
        image = np.asarray(bytearray(f.read()), dtype="uint8")
        image = cv2.imdecode(image, cv2.IMREAD_COLOR)
        # 识别结果
        plates = HyperLPR_plate_recognition(image)
        print(plates)
        # [['川A00000', 0.9829636641911098, [256, 184, 391, 231]]]
        arr = []
        for plate in plates:
            label = plate[0]
            confidence = plate[1]
            point = plate[2]
            arr.append({
    
    'label': label, 'confidence': confidence, 'point': point})
        plates_info = {
    
    'plates': arr}
        res = {
    
    "rc": 0, 'data': plates_info}
    else:
        # 如果文件为空
        res = {
    
    "rc": -1}
    return json.dumps(res, ensure_ascii=False)  # 防止出现乱码

@sever.route("/hyperlpr_base64.do", methods=["post"])
def hyperlpr_base64():
    # 上传文件,取一个名字,再给名字一个默认值None
    raw_data = flask.request.get_data("data")
    if raw_data:
        # print(raw_data)
        raw_json = json.loads(raw_data)
        image_base64 = raw_json['images'][0]
        # print(image_base64)
        image_bytes = np.asarray(bytearray(base64.b64decode(image_base64)), dtype="uint8")
        # print(image_bytes)
        image = cv2.imdecode(image_bytes, cv2.IMREAD_COLOR)
        # 识别结果
        plates = HyperLPR_plate_recognition(image)
        print(plates)
        # [['川A00000', 0.9829636641911098, [256, 184, 391, 231]]]
        arr = []
        for plate in plates:
            label = plate[0]
            confidence = plate[1]
            point = plate[2]
            arr.append({
    
    'label': label, 'confidence': confidence, 'point': point})
        plates_info = {
    
    'plates': arr}
        res = {
    
    "rc": 0, 'data': plates_info}
        # res = {
    
    "rc": 0}
    else:
        # 如果文件为空
        res = {
    
    "rc": -1}
    return json.dumps(res, ensure_ascii=False)  # 防止出现乱码


sever.run(host='0.0.0.0', port=8888)

Copy the above script to a certain directory of the server, copy it here to /home/hyperlpr/, create a new file hyperlpr_server.py
insert image description here
to start the background service

nohup python -u hyperlpr_server.py > log.txt 2>&1 &

If an error is reported when running the service:
nohup: ignoring input
Traceback (most recent call last):
File “hyperlpr_server.py”, line 5, in
import cv2
File “/anaconda3/envs/hyperlpr_env/lib/python3.8/site-packages/cv2/ init .py”, line 3, in
from .cv2 import *
Import Error: libSM.so.6: cannot open shared object file: No such file or directory
Solution: Refer to the following document to solve https://www.cnblogs.com/funykatebird/p/14715567.html
I am using 64-bit Centos7 here, and the installation steps are as follows:

sudo yum install libSM-1.2.2-2.el7.x86_64 --setopt=protected_multilib=false
sudo yum install libXrender-0.9.10-1.el7.x86_64 --setopt=protected_multilib=false
sudo yum install mesa-libGL.x86_64

view progress

ps -ef|grep python

close process

kill -9 19913

view log

tail -f 1000 log.txt

How to Check Port Occupation

$: netstat -anp | grep 8888
tcp        0      0 127.0.0.1:8888          0.0.0.0:*               LISTEN      13404/python3       
tcp        0      1 172.17.0.10:34036       115.42.35.84:8888       SYN_SENT    14586/python3 

Forcibly kill the process: by pid

$: kill -9 13404
$: kill -9 14586
$: netstat -anp | grep 8888

remote call demo

  • Use Postman to submit demo data
    insert image description here
    and return results:
{
    
    
    "rc": 0,
    "data": {
    
    
        "plates": [
            {
    
    
                "label": "京G65467",
                "confidence": 0.9797496455056327,
                "point": [
                    203,
                    440,
                    302,
                    473
                ]
            }
        ]
    }
}

Server deployment file download: https://download.csdn.net/download/loutengyuan/86773203

Guess you like

Origin blog.csdn.net/loutengyuan/article/details/126531910