目标
????????对以下两张图片进行检测,如果机器检测到戴口罩则使用绿色框选出来,若未带口罩则用红色框选出来。?
??
?展示结果
?
?方案
????????在这里我使用百度提供的免费智能平台人脸口罩检测与识别_口罩检测识别-百度AI开放平台 (baidu.com),方便可靠,不需要去训练大量的模型,百度提供的函数接口方便调用。使用opencv画线,显示图片等函数,来展示我的效果。
代码展示
1.导入需要的库
from aip import AipFace
import cv2 as cv
import base64
from pprint import pprint
2.""" 你的 APPID AK SK """
APP_ID = '***'
API_KEY = '***'
SECRET_KEY = '***'
client = AipFace(APP_ID, API_KEY, SECRET_KEY)
3.读取图片转换成base64的格式
def get_file_content(filePath):
with open(filePath, 'rb') as fp:
return fp.read()
def imgToBase64(imgPath):
with open(imgPath, "rb") as f: # 转为二进制格式
base64_data = base64.b64encode(f.read()) # 使用base64进行加密
return base64_data
?4.框选人脸,展示结果
def rectangle_face():
if content_decoded['error_code']==0:
result = content_decoded['result']
print("一共有%s个人"%result['face_num'])
#对每一个人进行边框,年龄,行别进行检测
for face in result['face_list']:
#只有当置信度大于0.8,认为成功检测到人脸
if face['face_probability']>0.8:
local = face['location']
if (face['mask']['type']) == 1 :
#画边框
cv.rectangle(src, (int(local['left']), int(local['top'])), (int(local['left']+local['width']),int(local['top']+local['height']) ), (0, 255, 0), thickness=2)
cv.putText(src, str(face['mask']['probability']), (int(local['left']), int(local['top']) - 10), cv.FONT_HERSHEY_SIMPLEX, 0.5,(0, 0, 255))
else:
# 画边框
cv.rectangle(src, (int(local['left']), int(local['top'])),(int(local['left'] + local['width']), int(local['top'] + local['height'])), (0, 0, 255),thickness=2)
# cv.putText(src, str(face['mask']['probability']), (int(local['left']), int(local['top']) - 10), cv.FONT_HERSHEY_SIMPLEX,0.5,(0, 0, 255))
cv.imshow("output",src)
?5.主要部分
src = cv.imread("D:/Python_image/mask2.png")
cv.namedWindow("input_image",cv.WINDOW_AUTOSIZE)
cv.imshow("intput_image",src)
img64 = imgToBase64("D:/Python_image/mask2.png").decode()
print(type(img64))
imageType = "BASE64"
""" 如果有可选参数 """
options = {}
options["face_field"] = "age,emotion,mask"
options["max_face_num"] = 10
options["face_type"] = "LIVE"
""" 带参数调用人脸检测 """
content_decoded = client.detect(img64, imageType, options)
pprint(content_decoded)
rectangle_face()
cv.waitKey(0)
cv.destroyALLWindows()
pprint打印出来的整个结构体可以研究研究,发现规律可以对需要检测部分的精度进行调整。
over----
|