The libfacedetection is an open-source library for detecting faces in images. It is based on a Convolutional Neural Network (CNN). The library includes a pre-trained CNN model that has been converted into C arrays and embedded directly in the source code. As a result, no separate model download is required before using the library. Additionally, libfacedetection has no external dependencies. This tutorial explains how to install precompiled libfacedetection on Raspberry Pi.
Install libfacedetection
Use SSH to connect to Raspberry Pi. Run the following command to download the .deb package from releases page of the repository:
curl -sSLo libfacedetection.deb https://github.com/prepkg/libfacedetection-raspberrypi/releases/latest/download/libfacedetection-aarch64-linux-gnu.deb
Now install libfacedetection with command:
sudo apt install -y ./libfacedetection.deb
The .deb package is no longer needed, remove it:
rm -rf libfacedetection.deb
Testing libfacedetection
For simplicity, install precompiled OpenCV for reading and writing image file. Also, GNU C++ compiler needs to be installed:
sudo apt install -y g++
Download image which will be used for testing:
curl -sSLo test.jpg https://raw.githubusercontent.com/ageitgey/face_recognition/master/examples/two_people.jpg
Now create a main.cpp file:
nano main.cpp
Add the following code:
#include <opencv2/opencv.hpp>
#include <facedetection/facedetectcnn.h>
using namespace cv;
int main() {
Mat img = imread("test.jpg");
unsigned char *buffer = (unsigned char *) malloc(FACEDETECTION_RESULT_BUFFER_SIZE);
int *results = facedetect_cnn(buffer, img.ptr(0), img.cols, img.rows, img.step);
for (int i = 0; i < *results; i++) {
short *p = ((short *) (results + 1)) + FACEDETECTION_RESULT_STRIDE_SHORTS * i;
int score = p[0];
int x = p[1];
int y = p[2];
int w = p[3];
int h = p[4];
if (score < 80) {
continue;
}
char text[4];
snprintf(text, sizeof(text), "%d", score);
putText(img, text, Point(x, y - 3), FONT_HERSHEY_SIMPLEX, 1, Scalar(0, 255, 0), 2);
rectangle(img, Rect(x, y, w, h), Scalar(0, 255, 0), 2);
}
imwrite("result.jpg", img);
free(buffer);
return 0;
}
The code detects faces in an image and draws bounding boxes around each detected face. A confidence score, ranging from 0 to 100, is also displayed next to each bounding box. Detections with a confidence score below 80 are skipped.
Compile code using the following command:
g++ main.cpp -o test -lfacedetection -lgomp -lopencv_core -lopencv_imgcodecs -lopencv_imgproc
Run a program:
./test
Output image is written to a specified file. Here is result:
Uninstall libfacedetection
If decided to completely remove libfacedetection, run the following command:
sudo apt purge --autoremove -y libfacedetection
Leave a Comment
Cancel reply