OpenCV的人脸检测模型FaceDetectorYN

打印 上一主题 下一主题

主题 1660|帖子 1660|积分 4980

1. 官网地址

https://docs.opencv.org/4.x/df/d20/classcv_1_1FaceDetectorYN.html
FaceDetectorYN是opencv内置的一个人脸检测方法,利用的是yunet。
这是一个DNN-based face detector.模型的下载地址:
https://github.com/opencv/opencv_zoo/tree/master/models/face_detection_yunet

2. 怎样利用

2.1.到opencv_zoo下载模型文件和代码


2.2. 下载文件展示


2.3. 修改了demo支持读取视频文件,默认是图片和摄像头

  1. # This file is part of OpenCV Zoo project.
  2. # It is subject to the license terms in the LICENSE file found in the same directory.
  3. #
  4. # Copyright (C) 2021, Shenzhen Institute of Artificial Intelligence and Robotics for Society, all rights reserved.
  5. # Third party copyrights are property of their respective owners.
  6. import argparse
  7. import numpy as np
  8. import cv2 as cv
  9. # Check OpenCV version
  10. opencv_python_version = lambda str_version: tuple(map(int, (str_version.split("."))))
  11. assert opencv_python_version(cv.__version__) >= opencv_python_version("4.10.0"), \
  12.     "Please install latest opencv-python for benchmark: python3 -m pip install --upgrade opencv-python"
  13. from yunet import YuNet
  14. # Valid combinations of backends and targets
  15. backend_target_pairs = [
  16.     [cv.dnn.DNN_BACKEND_OPENCV, cv.dnn.DNN_TARGET_CPU],
  17.     [cv.dnn.DNN_BACKEND_CUDA, cv.dnn.DNN_TARGET_CUDA],
  18.     [cv.dnn.DNN_BACKEND_CUDA, cv.dnn.DNN_TARGET_CUDA_FP16],
  19.     [cv.dnn.DNN_BACKEND_TIMVX, cv.dnn.DNN_TARGET_NPU],
  20.     [cv.dnn.DNN_BACKEND_CANN, cv.dnn.DNN_TARGET_NPU]
  21. ]
  22. parser = argparse.ArgumentParser(
  23.     description='YuNet: A Fast and Accurate CNN-based Face Detector (https://github.com/ShiqiYu/libfacedetection).')
  24. parser.add_argument('--input', '-i', type=str,
  25.                     help='Usage: Set input to a certain image, omit if using camera.')
  26. parser.add_argument('--model', '-m', type=str, default='face_detection_yunet_2023mar.onnx',
  27.                     help="Usage: Set model type, defaults to 'face_detection_yunet_2023mar.onnx'.")
  28. parser.add_argument('--backend_target', '-bt', type=int, default=0,
  29.                     help='''Choose one of the backend-target pair to run this demo:
  30.                         {:d}: (default) OpenCV implementation + CPU,
  31.                         {:d}: CUDA + GPU (CUDA),
  32.                         {:d}: CUDA + GPU (CUDA FP16),
  33.                         {:d}: TIM-VX + NPU,
  34.                         {:d}: CANN + NPU
  35.                     '''.format(*[x for x in range(len(backend_target_pairs))]))
  36. parser.add_argument('--conf_threshold', type=float, default=0.7,
  37.                     help='Usage: Set the minimum needed confidence for the model to identify a face, defauts to 0.9. Smaller values may result in faster detection, but will limit accuracy. Filter out faces of confidence < conf_threshold.')
  38. parser.add_argument('--nms_threshold', type=float, default=0.3,
  39.                     help='Usage: Suppress bounding boxes of iou >= nms_threshold. Default = 0.3.')
  40. parser.add_argument('--top_k', type=int, default=5000,
  41.                     help='Usage: Keep top_k bounding boxes before NMS.')
  42. parser.add_argument('--save', '-s', action='store_true',
  43.                     help='Usage: Specify to save file with results (i.e. bounding box, confidence level). Invalid in case of camera input.')
  44. parser.add_argument('--vis', '-v', action='store_true',
  45.                     help='Usage: Specify to open a new window to show results. Invalid in case of camera input.')
  46. parser.add_argument('--camera_or_video', '-c', default='123.mov',
  47.                     help='Usage: Specify to open camera or video')
  48. args = parser.parse_args()
  49. def visualize(image, results, box_color=(0, 255, 0), text_color=(0, 255, 255), fps=None):
  50.     output = image.copy()
  51.     landmark_color = [
  52.         (0, 0, 255),  # right eye
  53.         (0, 0, 255),  # left eye
  54.         (0, 255, 0),  # nose tip
  55.         (255, 0, 255),  # right mouth corner
  56.         (0, 255, 255)  # left mouth corner
  57.     ]
  58.     if fps is not None:
  59.         cv.putText(output, 'FPS: {:.2f}'.format(fps), (50, 50), cv.FONT_HERSHEY_SIMPLEX, 1.5, text_color)
  60.     for det in results:
  61.         bbox = det[0:4].astype(np.int32)
  62.         cv.rectangle(output, (bbox[0], bbox[1]), (bbox[0] + bbox[2], bbox[1] + bbox[3]), box_color, 2)
  63.         conf = det[-1]
  64.         cv.putText(output, '{:.4f}'.format(conf), (bbox[0], bbox[1] + bbox[3] // 2), cv.FONT_HERSHEY_DUPLEX, 1.5, text_color)
  65.         landmarks = det[4:14].astype(np.int32).reshape((5, 2))
  66.         for idx, landmark in enumerate(landmarks):
  67.             cv.circle(output, landmark, 4, landmark_color[idx], 10)
  68.     return output
  69. if __name__ == '__main__':
  70.     backend_id = backend_target_pairs[args.backend_target][0]
  71.     target_id = backend_target_pairs[args.backend_target][1]
  72.     # Instantiate YuNet
  73.     model = YuNet(modelPath=args.model,
  74.                   inputSize=[320, 320],
  75.                   confThreshold=args.conf_threshold,
  76.                   nmsThreshold=args.nms_threshold,
  77.                   topK=args.top_k,
  78.                   backendId=backend_id,
  79.                   targetId=target_id)
  80.     # If input is an image
  81.     if args.input is not None:
  82.         image = cv.imread(args.input)
  83.         h, w, _ = image.shape
  84.         # Inference
  85.         model.setInputSize([w, h])
  86.         results = model.infer(image)
  87.         # Print results
  88.         print('{} faces detected.'.format(results.shape[0]))
  89.         for idx, det in enumerate(results):
  90.             print(
  91.                 '{}: {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f} {:.0f}'.format(
  92.                     idx, *det[:-1])
  93.             )
  94.         # Draw results on the input image
  95.         image = visualize(image, results)
  96.         # Save results if save is true
  97.         if args.save:
  98.             print('Resutls saved to result.jpg\n')
  99.             cv.imwrite('result.jpg', image)
  100.         # Visualize results in a new window
  101.         if args.vis:
  102.             cv.namedWindow(args.input, cv.WINDOW_AUTOSIZE)
  103.             cv.imshow(args.input, image)
  104.             cv.waitKey(0)
  105.     else:  # Omit input to call default camera
  106.         deviceId = args.camera_or_video
  107.         cap = cv.VideoCapture(int(deviceId) if deviceId.isdigit() else deviceId)
  108.         w = int(cap.get(cv.CAP_PROP_FRAME_WIDTH))
  109.         h = int(cap.get(cv.CAP_PROP_FRAME_HEIGHT))
  110.         model.setInputSize([w, h])
  111.         fps = int(cap.get(cv.CAP_PROP_FPS))
  112.         # 定义视频编码器和创建VideoWriter对象
  113.         fourcc = cv.VideoWriter_fourcc(*'mp4v')  # 或者使用 'XVID'
  114.         out = cv.VideoWriter('output.mp4', fourcc, fps, (w, h))
  115.         tm = cv.TickMeter()
  116.         while cv.waitKey(1) < 0:
  117.             # Inference
  118.             tm.start()
  119.             hasFrame, frame = cap.read()
  120.             if not hasFrame:
  121.                 print('No frames grabbed!')
  122.                 break
  123.             results = model.infer(frame)  # results is a tuple
  124.             tm.stop()
  125.             # Draw results on the input image
  126.             frame = visualize(frame, results, fps=tm.getFPS())
  127.             # Visualize results in a new Window
  128.             cv.imshow('YuNet face detection', frame)
  129.             # tm.reset()
  130.             # 写入视频文件
  131.             out.write(frame)
  132.         out.release()
  133.         cap.release()
  134. cv.destroyAllWindows()
复制代码
## 2.4 效果展示


     吕一_faces_detection
  

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

汕尾海湾

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表