当前位置:   article > 正文

通过MediaPipe+MiDaS实现人脸单目测距

mediapipe

      MediaPipe:是Google开发的适用于直播和流媒体的开源、跨平台、可定制的机器学习解决方案。code地址:https://github.com/google/mediapipe ,最新发布版本v0.10.11,license为Apache-2.0。MediaPipe Solutions提供了一套库和工具,供你在应用程序中快速应用人工智能(AI)和机器学习(ML)技术,包括:目标检测、图像分类、图像分割、人脸检测等。

      MiDaS:开源的单目深度估计实现,地址:https://github.com/isl-org/MiDaS ,license为MIT。

      通过Anaconda搭建开发环境,依次执行如下命令:

  1. conda create -n MediaPipe python=3.9
  2. conda activate MediaPipe
  3. pip install mediapipe
  4. pip install requests
  5. git clone https://github.com/fengbingchun/NN_Test
  6. cd NN_Test/demo/Python

      以下为测试代码:

  1. import sys
  2. import os
  3. import cv2
  4. import requests
  5. import mediapipe as mp
  6. def download_onnx_model(url, model_name):
  7. if os.path.exists(model_name) and os.path.isfile(model_name):
  8. return
  9. response = requests.get(url, stream=True)
  10. if response.status_code == 200:
  11. print("Downloading ... ...")
  12. with open(model_name, "wb") as f:
  13. for chunk in response.iter_content(chunk_size=8192):
  14. if chunk:
  15. f.write(chunk)
  16. print("file downloaded successfully:", model_name)
  17. else:
  18. raise Exception("Error: unable to download file: {}".format(model_name))
  19. def get_images(dir, img_suffix):
  20. #print("dir:{}, img suffix:{}".format(dir, img_suffix))
  21. imgs = []
  22. for img in os.listdir(dir):
  23. if img.endswith(img_suffix):
  24. imgs.append(dir+"/"+img)
  25. return imgs
  26. def depth_to_distance(depth) -> float:
  27. return -1.5 * depth + 2
  28. def calc_distance(imgs, model_name):
  29. for img in imgs:
  30. bgr = cv2.imread(img, 1)
  31. if bgr is None:
  32. print("Error: image {} can't be read".format(bgr))
  33. continue
  34. rgb = cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB)
  35. height, width, channels = rgb.shape
  36. # define mediapipe face detection model
  37. face_detection_model = mp.solutions.face_detection.FaceDetection(min_detection_confidence=0.5, model_selection=0)
  38. # load monocular depth estimation model
  39. mono_model = cv2.dnn.readNet(model_name)
  40. # detect faces
  41. face_results = face_detection_model.process(rgb)
  42. if face_results.detections:
  43. for face in face_results.detections:
  44. # draw bounding boxes around the detected faces
  45. mp.solutions.drawing_utils.draw_detection(rgb, face)
  46. # in 0-1 scale
  47. boundary_box = face.location_data.relative_bounding_box
  48. # scale up to the image size
  49. boundary_box_scaled = int(boundary_box.xmin * width), int(boundary_box.ymin * height), int(boundary_box.width * width), int(boundary_box.height * height)
  50. # display the face detection score
  51. cv2.putText(rgb, f'{int(face.score[0]*100)}%', (boundary_box_scaled[0], boundary_box_scaled[1] - 20), cv2.FONT_HERSHEY_SIMPLEX, 2, (0,255,0), 2)
  52. # interest point of depth in a face. The center will be measured.
  53. interest_point = (boundary_box_scaled[0] + boundary_box_scaled[2] / 2, boundary_box_scaled[1] + boundary_box_scaled[3] / 2)
  54. # MiDaS v2.1 Small (Scale: 1/255, Size: 256x256, Mean Subtraction: (123.675, 116.28, 103.53), Channels Order: RGB,swapRB=True, crop=False)
  55. blob = cv2.dnn.blobFromImage(rgb, 1/255., (256,256), (123.675, 116.28, 103.53), True, False)
  56. # set the input into the model
  57. mono_model.setInput(blob)
  58. # get depth map
  59. depth_map = mono_model.forward()
  60. # resize it to the real world
  61. depth_map = depth_map[0,:,:]
  62. depth_map = cv2.resize(depth_map, (width, height))
  63. depth_map = cv2.normalize(depth_map, None, 0, 1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)
  64. # change colors to display it in OpenCV
  65. bgr = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)
  66. # get the depth of the point of interest
  67. depth = depth_map[int(interest_point[0]), int(interest_point[1])]
  68. depth_distance = depth_to_distance(depth)
  69. cv2.putText(bgr, f"Depth to face: {str(round(depth_distance,2)*100)} cm", (40,600), cv2.FONT_HERSHEY_SIMPLEX, 2, (0,0,255), 2)
  70. cv2.imwrite("../../data/result_"+os.path.basename(img), bgr)
  71. if __name__ == "__main__":
  72. if len(sys.argv) != 3:
  73. raise Exception("Usage: requires two parameters, for example: python {} directory_name image_suffix_name".format(sys.argv[0]))
  74. model_name = "model-small.onnx"
  75. download_onnx_model("https://github.com/isl-org/MiDaS/releases/download/v2_1/model-small.onnx", model_name)
  76. imgs = get_images(sys.argv[1], sys.argv[2])
  77. #print("imgs:", imgs)
  78. calc_distance(imgs, model_name)
  79. print("test finish")

      说明

      1.测试代码参考:https://levelup.gitconnected.com

      2.mp.solutions.face_detection.FaceDetection函数中,model_selection默认为0;距离相机2米以内的脸部检测模型设置为0,即short_range;距离相机5米以内的脸部检测模型设置为1,即full_range。

      3.model-small.onnx为预训练的单目深度估计模型,从https://github.com/isl-org/MiDaS/releases/tag/v2_1 下载;如果有cuda,也可以使用更大的模型获得更真实的结果。

      4.depth_to_distance函数用于将深度图值转换为以厘米为单位的真实世界的距离,此转换的公式根据你的网络摄像头配置而有所不同。注:还不清楚此公式怎么来的

      5.测试代码接收2个参数,第一个参数指定存放图像的路径,第二个参数指定图像后缀名;首次运行会自动下载onnx模型。

      运行结果如下图所示:

      测试图像执行结果如下图所示:原始图像来自于网络

      GitHubhttps://github.com/fengbingchun/NN_Test

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/神奇cpp/article/detail/906104
推荐阅读
相关标签
  

闽ICP备14008679号