2020年,肆虐全球的新冠肺炎让我们的生活按下了暂停键,如今全球疫情形式依旧不容乐观。
由于疫情的影响,人脸口罩检测系统的开发成为很多人争相开发的一种算法。很多公司或者个人都开源了他们很多的代码或者SDK。大家在GitHub或者各种平台上都能够找到很多的资源。
这个暑假,借着返校遥遥无期,在家闲来无事的时候,我自己研究了一下目前在网上的开源代码,利用百度公司之前的开源模型Paddlehub,来实现人脸口罩识别。
使用工具
系统 Windows 10
语言 Python 3.7
第三方库 OpenCV
Paddlehub
利用Paddlehub识别照片
import paddlehub as hub
# 1.待预测图片
test_img_path = ["115.png"]
# 2.载入模型
module = hub.Module(name="pyramidbox_lite_mobile_mask")
# 3.预测
input_dict = {"image": test_img_path}
results = module.face_detection(data=input_dict)
运行上述代码后我们可以在文件夹detection_result中得到我们的检测结果
图片中No mask表示没有佩戴口罩, No mask旁边的数字代表可信度。
利用笔记本电脑自带摄像头实现口罩识别
通过查阅其他开源到csdn的代码,我根据上述代码,利用OpenCV第三方库调用笔记本电脑自带摄像头,我并利用第三方库tkinter编写了GUI界面,具体代码如下:
from tkinter import *
import cv2 as cv
from PIL import Image, ImageTk
import paddlehub as hub
#摄像机设置
#0是代表摄像头编号,只有一个的话默认为0
capture=cv.VideoCapture(0)
def getframe():
ref,frame=capture.read()
cv.imwrite(tempimagepath,frame)
def closecamera():
capture.release()
#界面相关
window_width=1280
window_height=960
image_width=int(window_width*0.8)
image_height=int(window_height*0.8)
imagepos_x=int(window_width*0.2)
imagepos_y=int(window_height*0.1)
butpos_x=600
butpos_y=800
top=Tk()
top.wm_title("mask recognition")
top.geometry(str(window_width)+'x'+str(window_height))
def tkImage(module):
ref,frame=capture.read()
input_dict={"data": [frame]}
results = module.face_detection(data=input_dict)
for result in results:
x1=int(result['data']['left'])
y1=int(result['data']['top'])
x2=int(result['data']['right'])
y2=int(result['data']['bottom'])
k2=result['data']['label']
if k2=='MASK':
frame=cv.rectangle(frame,(x1,y1),(x2,y2),(0,255,0),2)
cv.putText(frame, k2, (x1 - 5, y1 - 10), cv.FONT_HERSHEY_PLAIN, 1.0, (0, 255, 0), 1)
else:
frame=cv.rectangle(frame,(x1,y1),(x2,y2),(0,0,255),2)
cv.putText(frame, k2, (x1 - 5, y1 - 10), cv.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 255), 1)
cvimage = cv.cvtColor(frame, cv.COLOR_BGR2RGBA)
pilImage=Image.fromarray(cvimage)
pilImage = pilImage.resize((image_width, image_height),Image.ANTIALIAS)
tkImage = ImageTk.PhotoImage(image=pilImage)
return tkImage
#控件定义
canvas =Canvas(top,bg='white',width=image_width,height=image_height)#绘制画布
#控件位置设置
canvas.place(x=imagepos_x,y=imagepos_y)
if __name__=="__main__":
module=hub.Module(name="pyramidbox_lite_mobile_mask")
while(True):
picture=tkImage(module)
canvas.create_image(0,0,anchor='nw',image=picture)
top.update()
top.after(100)
top.mainloop()
closecamera()
运行上述程序后,我们即可得到下述软件界面,如图所示:
这些就是我做出来的一些成果,希望对大家有用。