Sitemap
Level Up Coding

Coding tutorials and news. The developer homepage gitconnected.com && skilled.dev && levelup.dev

YuNet implementation in OpenCV-Python

--

Picture from Google.

I searched a lot for a proper YuNet face detector implementation in Python but I am surprised that there aren't any good ones. This post will talk about YuNet, an elementary and accurate face detector that can be used in both Python and C++ libraries.

I will just get to the code part then we can talk more about this later on.

First, you need to download the onnx model file from GitHub. This should be a .onnx file for the YuNet. You also need the OpenCV-python package to be installed and a test image where you want to test YuNet’s performance.

The code is as below.

# Initialize detector
detector = cv2.FaceDetectorYN.create("yunet_n_320_320.onnx", "", (320, 320))
# Read image
img = cv2.imread("image.jpg")
# Get image shape
img_W = int(img.shape[1])
img_H = int(img.shape[0])
# Set input size
detector.setInputSize((img_W, img_H))
# Getting detections
detections = detector.detect(img)

We are specifying the input size of the model to be 320 by 320. This should be the size of the input image. So we need to convert the input image to this size before passing it on to the model for inference.

Another way is to get the input size dynamically by getting the image shape after reading the image by openCV. We set the input size afterward by detector.setInputSize((img_W, img_H)) .

For the inference, it is just the detector.detect(img) .

Get Jubayer Hossain Ahad’s stories in your inbox

Join Medium for free to get updates from this writer.

For the output which is saved in the detections variable, it is a list of detections. For each of the detections, we get an array of size 15. The first 4 values from dets[0:4] are the value of the bounding box as [top_x, top_y, width, height].

The YuNet face detection model provides coordinates for five facial landmarks. Here’s the detailed breakdown:

  1. Right Eye: ((dets[:, 4], dets[:, 5]))
  2. Left Eye: ((dets[:, 6], dets[:, 7]))
  3. Nose Tip: ((dets[:, 8], dets[:, 9]))
  4. Right Mouth Corner: ((dets[:, 10], dets[:, 11]))
  5. Left Mouth Corner: ((dets[:, 12], dets[:, 13]))

And finally, the 15th value or dets[15] is the confidence score for the detection.

I am making an emotion detection script for a multi-camera system project where the first step is detecting the faces from the camera. If you want to see the progress of the project, consider following me here on Medium.

If you found value in this article, drop a clap and let me know if you have any questions regarding this.

--

--

Jubayer Hossain Ahad
Jubayer Hossain Ahad

Written by Jubayer Hossain Ahad

Machine Learning Engineer. Research Assistant at Pattern Recognition Lab, FAU. Studying Masters in ElectroMobility at FAU, Germany.