Skip to content

Instantly share code, notes, and snippets.

@UnaNancyOwen
Last active September 4, 2023 11:07
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save UnaNancyOwen/3f06d4a0d04f3a75cc62563aafbac332 to your computer and use it in GitHub Desktop.
Save UnaNancyOwen/3f06d4a0d04f3a75cc62563aafbac332 to your computer and use it in GitHub Desktop.
OpenCV ObjDetect Module Face Detection (YuNet/libfacedetection) Sample
import os
import numpy as np
import cv2
def main():
# キャプチャを開く
directory = os.path.dirname(__file__)
#capture = cv2.VideoCapture(os.path.join(directory, "image.jpg")) # 画像ファイル
capture = cv2.VideoCapture(0) # カメラ
if not capture.isOpened():
exit()
# モデルを読み込む
weights = os.path.join(directory, "yunet.onnx")
face_detector = cv2.FaceDetectorYN_create(weights, "", (0, 0))
while True:
# フレームをキャプチャして画像を読み込む
result, image = capture.read()
if result is False:
cv2.waitKey(0)
break
# 画像が3チャンネル以外の場合は3チャンネルに変換する
channels = 1 if len(image.shape) == 2 else image.shape[2]
if channels == 1:
image = cv2.cvtColor(image, cv2.COLOR_GRAY2BGR)
if channels == 4:
image = cv2.cvtColor(image, cv2.COLOR_BGRA2BGR)
# 入力サイズを指定する
height, width, _ = image.shape
face_detector.setInputSize((width, height))
# 顔を検出する
_, faces = face_detector.detect(image)
faces = faces if faces is not None else []
# 検出した顔のバウンディングボックスとランドマークを描画する
for face in faces:
# バウンディングボックス
box = list(map(int, face[:4]))
color = (0, 0, 255)
thickness = 2
cv2.rectangle(image, box, color, thickness, cv.LINE_AA)
# ランドマーク(右目、左目、鼻、右口角、左口角)
landmarks = list(map(int, face[4:len(face)-1]))
landmarks = np.array_split(landmarks, len(landmarks) / 2)
for landmark in landmarks:
radius = 5
thickness = -1
cv2.circle(image, landmark, radius, color, thickness, cv2.LINE_AA)
# 信頼度
confidence = face[-1]
confidence = "{:.2f}".format(confidence)
position = (box[0], box[1] - 10)
font = cv2.FONT_HERSHEY_SIMPLEX
scale = 0.5
thickness = 2
cv2.putText(image, confidence, position, font, scale, color, thickness, cv2.LINE_AA)
# 画像を表示する
cv2.imshow("face detection", image)
key = cv2.waitKey(10)
if key == ord('q'):
break
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
@610t
Copy link

610t commented Mar 3, 2022

45行目のLINE_AAの指定がcv2ではなく、cvとなっています。
x cv2.rectangle(image, box, color, thickness, cv.LINE_AA)
o cv2.rectangle(image, box, color, thickness, cv2.LINE_AA)

@ayanatherate
Copy link

Hi @UnaNancyOwen. First of all, Great work!
The link to download the model (yunet.onnx) does not seem to be working now for some reason. Can you kindly look into it?
Thanks!

@anilsathyan7
Copy link

anilsathyan7 commented Oct 25, 2022

@ayanatherate There is a model at https://github.com/opencv/opencv_zoo/tree/master/models/face_detection_yunet.
i.e face_detection_yunet_2022mar.onnx

@lynnwilliam
Copy link

There is a model at https://github.com/opencv/opencv_zoo/tree/master/models/face_detection_yunet.
i.e face_detection_yunet_2022mar.onnx

This model is NOT compatible with your sample project.
That is an updated model that has bugs listed in
ShiqiYu/libfacedetection#294

But if you can get your project working with the new ONNX model let me know.
As far as I know it just doesn't work correctly.

@JamesAkers2022
Copy link

Works perfectly, just had to change the source onnx file (sort of like a .xml cascade file) to exclude the path, (currently using "face_detection_yunet_2022mar.onnx")
. Also had to add a "2" after a "cv" and before "LINE_AA"

TIme to pick at it and see if I can add so me little if statements in there to control things

@AlessandroMondin
Copy link

The only source online!
As said by @JamesAkers2022 those two are the only problems!
Thanks a lot!

@lynnwilliam
Copy link

Can someone link to the fixed file here for submit a pull request ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment