前言
本次实现了一个在浏览器中运行的简陋的人脸检测功能,由于水平有限,这里使用表单上传图片,只能一次检测一张人脸。实现过程中遇到的主要问题是数据格式转换的问题。
分析与设计
之前已经成功基于AI分词模型,构建了一个Web应用。套路大致相同,与本次任务的主要区别在于,本次传递的数据是图像而不是文本。图像数据会带来一个新的问题:
- 图像的编码方式丰富,数据处理过程中需要进行一些数据格式转换。
应用的逻辑大致如下:
- 1.用户通过表单从浏览器上传图像
- 2.将图像转发给人脸检测模型,得到人脸位置坐标
- 3.使用矩形框出图像中的人脸
- 4.浏览器显示结果
实现
1. 部署人脸检测模型
一行命令即可完成服务化部署(你需要先安装PaddleHub库),pyramidbox_lite_mobile是一个预训练的人脸检测模型。
1
|
hub serving start - m pyramidbox_lite_mobile |
你可以使用下面的代码(来自PaddleHub的文档,记得修改未你自己的图片存放路径),测试接口:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
# coding: utf8 import requests import json import cv2 import base64 def cv2_to_base64(image): data = cv2.imencode( '.jpg' , image)[ 1 ] return base64.b64encode(data.tostring()).decode( 'utf8' ) if __name__ = = '__main__' : # 获取图片的base64编码格式 (记得修改你自己的图片存放路径) img1 = cv2_to_base64(cv2.imread( "./static/Aaron_Peirsol_0001.jpg" )) img2 = cv2_to_base64(cv2.imread( "./static/Aaron_Peirsol_0002.jpg" )) data = { 'images' : [img1, img2]} # 指定content-type headers = { "Content-type" : "application/json" } # 发送HTTP请求 url = "http://127.0.0.1:8866/predict/pyramidbox_lite_mobile" r = requests.post(url = url, headers = headers, data = json.dumps(data)) # 打印预测结果 print (r.json()) |
2. 使用Flask构建app
2.1 目录结构
1
2
3
4
5
|
- templates - index.html - app.py - forms.py - utils.py |
其中utils.py封装了一些简单的函数。
2.2 forms.py
下面定义了一个表单,它只有一个字段face_img,用于上传待检测的人脸图片。validatiors中描述了很多message,在上传的表单不满足约束时,可在html模板中通过{{ form.face_img.erros }}获取相关的message信息。
1
2
3
4
5
6
7
8
9
10
11
12
|
from flask_wtf import FlaskForm from flask_wtf. file import FileAllowed, FileRequired, FileSize, FileField class ImageForm(FlaskForm): face_img = FileField( "face_img" , validators = [ FileRequired(message = "不能为空" ), FileAllowed([ 'jpg' , 'png' ], message = "仅支持jpg/png格式" ), FileSize(max_size = 2048000 , message = "图片不能大于2Mb" ) ], description = "图片不能大于2Mb,仅支持jpg/png格式" ) |
2.3 utils.py
封装了三个简单的函数,但在app.py中只使用了cv2_to_base64()。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
import base64 import numpy as np import cv2 def base64_to_cv2(img: str ): # base64 -> 二进制 -> ndarray -> cv2 # 解码为二进制数据 img_codes = base64.b64decode(img) img_np = np.frombuffer(img_codes, np.uint8) img_cv2 = cv2.imdecode(img_np, cv2.IMREAD_COLOR) return img_cv2 def cv2_to_base64(image): data = cv2.imencode( '.jpg' , image)[ 1 ] return base64.b64encode(data.tostring()).decode( 'utf8' ) # 显示cv2格式的图像 --> 开发过程中测试图像是否正常时使用 def cv2_show(img_cv2): cv2.imshow( 'img' , img_cv2) cv2.waitKey( 0 ) cv2.destroyAllWindows() |
2.4 app.py
注:如果以后数据在转换的过程中究竟变成了什么格式,那就把它们打印出来看看叭!例如print(data, type(data))。
主要的逻辑就在这里了,图像主要经历了三种类型的格式:
- 文件对象:从前端表单返回的图像文件的格式。
- cv2:opencv的图像格式,是一个numpy的ndarray数组。
- str:base64编码格式的字符串;是作为模型输入,和在前端显示图像的格式。
数据格式的变化流程大致如下图:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
# 注:在推理前将图像缩放到指定的尺寸,即能提升速度,有时也能提升精度(实测像素太高时识别效果也不好) from flask import Flask, render_template, request import requests from forms import ImageForm import cv2 import numpy as np import json import time from utils import cv2_to_base64 app = Flask(__name__) app.config[ 'SECRET_KEY' ] = 'your_secret_key_here' @app .route( '/' , methods = [ 'GET' , 'POST' ]) def predict(): form = ImageForm() if form.validate_on_submit(): # 1. 从前端表单获取图像文件 file = form.face_img.data # <class 'werkzeug.datastructures.FileStorage'> file_content = file .read() # <class 'bytes'> # 2. 图像文件转cv2, 并缩放到指定尺寸 --> 尺寸太大或太小,识别精度都会变差 img_cv2 = np.asarray(bytearray(file_content), dtype = np.uint8) # (len,) img_cv2 = cv2.imdecode(img_cv2, cv2.IMREAD_COLOR) # (w, h, c) img_cv2 = cv2.resize(img_cv2, ( 250 , 250 ), interpolation = cv2.INTER_LINEAR) # 3. cv2转str(base64) img_base64 = cv2_to_base64(img_cv2) # 4. str(base64)输入模型 --> json --> 人脸框坐标 data = { 'images' : [img_base64]} headers = { "Content-type" : "application/json" } url = "http://127.0.0.1:8866/predict/pyramidbox_lite_mobile" start_time = time.time() r = requests.post(url = url, headers = headers, data = json.dumps(data)) use_time = time.time() - start_time rectangle = r.json()[ 'results' ][ 0 ][ 'data' ][ 0 ] # 一张图片 --> dict{confidence, left, top, right, bottom} # 5. cv2,json --> 画矩形 --> cv2 cv2.rectangle( img_cv2, (rectangle[ 'left' ], rectangle[ 'top' ]), (rectangle[ 'right' ], rectangle[ 'bottom' ]), ( 255 , 0 , 0 ), # 蓝色 thickness = 2 ) # 6. cv2转str(base64) img_base64 = cv2_to_base64(img_cv2) # 7. str(base64) 返回到前端 return render_template( 'index.html' , form = form, img_base64 = img_base64, confidence = rectangle[ 'confidence' ], use_time = use_time) return render_template( 'index.html' , form = form) if __name__ = = '__main__' : app.run(debug = True , port = 5000 ) |
2.5 index.html
视图模板,也是十分简陋。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
<h1>试试人脸检测< / h1> <! - - 1. 上传图像的表单 - - > <form action = " " method=" post " class=" mt - 4 " enctype=" multipart / form - data"> <! - - csrf这一句好像可以没啥用 - - > {{ form.csrf_token }} {{ form.face_img() }} < input type = "submit" value = "Submit" > < / form> <! - - 2. 显示检测结果 - - > { % if img_base64 % } <img src = "data:image/jpeg;base64, {{ img_base64 }}" width = "250" height = "250" > <p>置信度: {{ confidence }}< / p> <p>推理耗时(秒): {{ use_time }}< / p> { % endif % } <! - - 3. 显示错误信息 - - > { % if form.face_img.errors % } <div class = "alert alert-danger" > { % for error in form.face_img.errors % } {{ error }} { % endfor % } < / div> { % endif % } |
Bug(s)
1、后端接收不到上传的图片
使用表单的模板代码如下:
1
2
3
4
5
6
|
<form action = " " method=" post " class=" mt - 4 "> <! - - csrf这一句好像可以删掉 - - > {{ form.csrf_token }} {{ form.face_img() }} < input type = "submit" value = "Submit" > < / form> |
解决:在 Flask 中处理文件上传时,需要<form>中添加 enctype="multipart/form-data" 属性,这样浏览器才能正确识别上传的文件数据。
2、数据格式转换晕头转向
在app.py中,我最初对于图像格式的转换十分懵圈,想整理下思路,结果却如下图,还是很乱。经过多次重构,才变成了 2.5 app.py 那里显示的图。
重构还是挺有用的!有时代码经过重构也会变得清晰。
到此这篇关于人脸检测——基于Flask和PaddleHub的文章就介绍到这了,更多相关人脸检测内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/m0_63238256/article/details/129636071