【Mind+Python】人脸检测

2021-08-071.7万
AI 快速预览详细 收起
本文介绍了如何使用Python的face_recognition包进行人脸检测,并用OpenCV在原图像中绘制人脸框和landmark关键点。首先,你需要安装face_recognition库。然后,通过调用face_recognition.face_locations()函数,可以获取图像中所有人脸的位置。接着,使用OpenCV的cv2.rectangle()函数绘制人脸框,并通过face_recognition.face_landmarks()函数获取landmark关键点,再用cv2.drawContours()函数绘制这些关键点。整个过程简单易懂,适合初学者和STEM教育项目。


python的“face_recognition”包进行人脸检测、用OpenCV在原图像中绘制人脸box框和landmark关键点。
【安装】
【Mind+Python】人脸检测图1

人脸检测face_recognition可以输出一幅图像中人脸框的左上和右下点的坐标
【Mind+Python】人脸检测图2

  1. import cv2
  2. import face_recognition
  3. cap = cv2.VideoCapture(0)
  4. while True:
  5.     ret, frame = cap.read()
  6.     frame = cv2.resize(frame, (0,0), fx=0.5, fy=0.5)
  7.     # Find all the faces in the video
  8.     face_locations = face_recognition.face_locations(frame)
  9.     number_of_faces = len(face_locations)
  10.     print("I found {} face(s) in this video.".format(number_of_faces))
  11.     for face_location in face_locations:
  12.         # Print the location of each face in this image. Each face is a list of co-ordinates in (top, right, bottom, left) order.
  13.         top, right, bottom, left = face_location
  14.         print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom,
  15.                                                                                                     right))
  16.         cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 3)
  17.     cv2.imshow("Frame", frame)
  18.     ch = cv2.waitKey(1)
  19.     if ch & 0xFF == ord('q'):
  20.         break
  21. cap.release()
  22. cv2.destroyAllWindows()
复制代码


landmark关键点face_recognition可输出如下图所示人脸五官的landmark坐标(共68个坐标点)。
【Mind+Python】人脸检测图3
  1. import numpy as np
  2. import cv2
  3. import face_recognition
  4. cap = cv2.VideoCapture(0)
  5. while True:
  6.     ret, frame = cap.read()
  7.     frame = cv2.resize(frame, (0,0), fx=0.5, fy=0.5)
  8.     # Find all facial features in all the faces in the video
  9.     face_landmarks_list = face_recognition.face_landmarks(frame)
  10.     for face_landmarks in face_landmarks_list:
  11.         # Loop over each facial feature (eye, nose, mouth, lips, etc)
  12.         for name, list_of_points in face_landmarks.items():
  13.             hull = np.array(face_landmarks[name])
  14.             hull_landmark = cv2.convexHull(hull)
  15.             cv2.drawContours(frame, hull_landmark, -1, (0, 255, 0), 3)
  16.     cv2.imshow("Frame", frame)
  17.     ch = cv2.waitKey(1)
  18.     if ch & 0xFF == ord('q'):
  19.         break
  20. cap.release()
  21. cv2.destroyAllWindows()
复制代码




创作许可协议

本项目采用 None(不开放任何权利,保留所有权利) 进行许可。

评论(0)
- 没有更多了 -