基于mediapipe进行的脸位置标记
采用方法
主要使用google 的 mediapipe 工具包中的face_detection模块和opencv中的显示标识模块
使用事项
文中的1.flv 可以换成其他格式的视频。
代码如下
import cv2
import mediapipe as mp
import time
class poseDetector():
def __init__(self, min_detection_confidence=0.75):
self.min_detection_confidence = min_detection_confidence
self.mpFace = mp.solutions.face_detection
self.face = self.mpFace.FaceDetection(self.min_detection_confidence)
self.mpDraw = mp.solutions.drawing_utils
def findPose(self, img, draw=True):
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
self.results = self.face.process(imgRGB)
bboxs = []
if self.results.detections:
for id, detection in enumerate(self.results.detections):
bboxC = detection.location_data.relative_bounding_box
ih, iw, ic = img.shape
bbox = int(bboxC.xmin * iw), int(bboxC.ymin * ih), \
int(bboxC.width * iw), int(bboxC.height * ih)
bboxs.append([id, bbox, detection.score])
if draw:
img = self.fancyDraw(img, bbox)
cv2.putText(img, f'{int(detection.score[0] * 100)}%',
(bbox[0], bbox[1] - 20), cv2.FONT_HERSHEY_PLAIN, 2, (255, 0, 255), 2)
return img, bboxs
def fancyDraw(self, img, bbox, l=30, t=5, rt=1):
x, y, w, h = bbox
x1, y1 = x + w, y + h
cv2.rectangle(img, bbox, (255, 0, 255), rt)
cv2.line(img, (x, y), (x + l, y), (255, 0, 255), t)
cv2.line(img, (x, y), (x, y + l), (255, 0, 255), t)
cv2.line(img, (x1, y), (x1 - l, y), (255, 0, 255), t)
cv2.line(img, (x1, y), (x1, y + l), (255, 0, 255), t)
cv2.line(img, (x, y1), (x + l, y1), (255, 0, 255), t)
cv2.line(img, (x, y1), (x, y1 - l), (255, 0, 255), t)
cv2.line(img, (x1, y1), (x1 - l, y1), (255, 0, 255), t)
cv2.line(img, (x1, y1), (x1, y1 - l), (255, 0, 255), t)
return img
def main():
pTime = 0
cap = cv2.VideoCapture('1.flv')
detector = poseDetector()
while True:
success, img = cap.read()
img, bboxs = detector.findPose(img)
cTime = time.time()
fps = 1 / (cTime - pTime)
pTime = cTime
cv2.putText(img, f"fps:{int(fps)}", (10, 70), cv2.FONT_HERSHEY_PLAIN, 3, (255, 0, 255), 3)
cv2.imshow('Image', img)
cv2.waitKey(1)
if __name__ == '__main__':
main()