百度飞桨
引用库:
import paddlehub as hub
import cv2
安装过程出现各种bug,按提示一一解决。
项目文件:
imgs文件夹保存待识别图片,2.mp4为待识别视频,result.jpg为图片识别结果。
maskpicture.py
图片检测
img_path = './imgs/2.jpg’中图片路径为待检测图片所在位置
import paddlehub as hub
import cv2
mask_detector = hub.Module(name="pyramidbox_lite_server_mask")
img_path = './imgs/2.jpg'
img = cv2.imread(img_path)
no = 0
yes = 0
input_dict = {"data": [img]}
result = mask_detector.face_detection(data=input_dict)
count = len(result[0]['data'])
if count < 1:
print('There is no face detected!')
else:
for i in range(0, count):
print(result[0]['data'][i])
label = result[0]['data'][i].get('label')
score = round(float(result[0]['data'][i].get('confidence')), 2)
x1 = int(result[0]['data'][i].get('left'))
y1 = int(result[0]['data'][i].get('top'))
x2 = int(result[0]['data'][i].get('right'))
y2 = int(result[0]['data'][i].get('bottom'))
rate = label + ":" + str(score)
cv2.rectangle(img, (x1, y1), (x2, y2), (255, 200, 0), 2)
if label == 'NO MASK':
no += 1
cv2.putText(img, rate, (x1, y1), 0, 0.8, (0, 0, 255), 2)
else:
yes += 1
cv2.putText(img, rate, (x1, y1), 0, 0.8, (0, 255, 0), 2)
cv2.imwrite('result.jpg', img)
cv2.imshow('mask-detection', img)
print('输出:\n')
print('戴口罩:%d人\n' % yes)
print('未戴口罩:%d人\n' % no)
cv2.waitKey()
cv2.destroyAllWindows()
print('Done!')
maskvideo.py
视频或摄像头检测
cap = cv2.VideoCapture(‘2.mp4’) # 视频文件检测
此处为视频路径
import paddlehub as hub
import cv2
mask_detector = hub.Module(name="pyramidbox_lite_server_mask")
def mask_detecion(img):
input_dict = {"data": [img]}
result = mask_detector.face_detection(data=input_dict)
count = len(result[0]['data'])
if count < 1:
# print('There is no face detected!')
pass
else:
for i in range(0, count):
# print(result[0]['data'][i])
label = result[0]['data'][i].get('label')
score = round(float(result[0]['data'][i].get('confidence')), 2)
x1 = int(result[0]['data'][i].get('left'))
y1 = int(result[0]['data'][i].get('top'))
x2 = int(result[0]['data'][i].get('right'))
y2 = int(result[0]['data'][i].get('bottom'))
cv2.rectangle(img, (x1, y1), (x2, y2), (255, 200, 0), 2)
rate = label + ":" + str(score)
if label == 'NO MASK':
cv2.putText(img, rate, (x1, y1), 0, 0.8, (0, 0, 255), 2)
else:
cv2.putText(img, rate, (x1, y1), 0, 0.8, (0, 255, 0), 2)
return img
if __name__ == '__main__':
cap = cv2.VideoCapture('2.mp4') # 视频文件检测
# cap = cv2.VideoCapture(0) #摄像头检测
if cap.isOpened(): # 视频打开成功
while True:
ret, frame = cap.read() # 读取一帧
result = mask_detecion(frame)
cv2.imshow('mask_detection', result)
if cv2.waitKey(1) & 0xFF == 27: # 按下Esc键退出
break
else:
print('open video/camera failed!')
cap.release()
cv2.destroyAllWindows()
摄像头样例
# cap = cv2.VideoCapture(0) #摄像头检测
将此句注释放开,上句注释为摄像头检测
图片样例
可正常输出统计戴口罩人数与未戴口罩人数。