added face detection comparison code

This commit is contained in:
Vikas Gupta committed 2018-10-18 14:19:49 +05:30
1 parent e1fc709495
commit 5d377e7013
23 files changed
+38622 -1

No files matched your search

+20
View File
@@ -0,0 +1,20 @@
cmake_minimum_required(VERSION 2.8.12)
PROJECT(face_detection)
find_package( OpenCV REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS})
include(./dlib/dlib/cmake)
MACRO(add_example name)
ADD_EXECUTABLE(${name} ${name}.cpp)
TARGET_LINK_LIBRARIES(${name} ${OpenCV_LIBS} dlib::dlib)
ENDMACRO()
add_example(face_detection_opencv_haar)
add_example(face_detection_opencv_dnn)
add_example(face_detection_dlib_hog)
add_example(face_detection_dlib_mmod)
add_example(run-all)
+31
View File
@@ -0,0 +1,31 @@
There are 10 code files in this repo - 5 for C++ and 5 for Python
1. face_detection_opencv_haar.cpp and face_detection_opencv_haar.py - For Haar based face detection
2. face_detection_opencv_dnn.cpp and face_detection_opencv_dnn.py - For OpenCV DNN based face detection
3. face_detection_dlib_hog.cpp and face_detection_dlib_hog.py - for dlib hog based face detection
4. face_detection_dlib_mmod.cpp and face_detection_dlib_mmod.py - for dlib mmod based face detection
5. run-all.cpp and run-all.py - for running all the 4 together
First of all Unzip the dlib.zip file
## For C++
**Compile**
cmake .
make
## Run
**If you dont give any filename, it will use the webcam**
### For individual face detectors
**C++**
./face_detection_XXXX <filename>
**Python**
python face_detection_XXXX.py <filename>
### For running all together
**C++**
./run-all <filename>
**Python**
run-all.py <filename>
Binary file not shown.
@@ -0,0 +1,79 @@
#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <dlib/opencv.h>
#include <dlib/image_processing.h>
#include <dlib/image_processing/frontal_face_detector.h>
using namespace cv;
using namespace std;
using namespace dlib;
void detectFaceDlibHog(frontal_face_detector hogFaceDetector, Mat &frameDlibHog, int inHeight=300, int inWidth=0)
{
int frameHeight = frameDlibHog.rows;
int frameWidth = frameDlibHog.cols;
if (!inWidth)
inWidth = (int)((frameWidth / (float)frameHeight) * inHeight);
float scaleHeight = frameHeight / (float)inHeight;
float scaleWidth = frameWidth / (float)inWidth;
Mat frameDlibHogSmall;
resize(frameDlibHog, frameDlibHogSmall, Size(inWidth, inHeight));
// Convert OpenCV image format to Dlib's image format
cv_image<bgr_pixel> dlibIm(frameDlibHogSmall);
// Detect faces in the image
std::vector<dlib::rectangle> faceRects = hogFaceDetector(dlibIm);
for ( size_t i = 0; i < faceRects.size(); i++ )
{
int x1 = (int)(faceRects[i].left() * scaleWidth);
int y1 = (int)(faceRects[i].top() * scaleHeight);
int x2 = (int)(faceRects[i].right() * scaleWidth);
int y2 = (int)(faceRects[i].bottom() * scaleHeight);
cv::rectangle(frameDlibHog, Point(x1, y1), Point(x2, y2), Scalar(0,255,0), (int)(frameHeight/150.0), 4);
}
}
int main( int argc, const char** argv )
{
frontal_face_detector hogFaceDetector = get_frontal_face_detector();
VideoCapture source;
if (argc == 1)
source.open(0);
else
source.open(argv[1]);
Mat frame;
double tt_dlibHog = 0;
double fpsDlibHog = 0;
while(1)
{
source >> frame;
if(frame.empty())
break;
double t = cv::getTickCount();
detectFaceDlibHog ( hogFaceDetector, frame );
tt_dlibHog = ((double)cv::getTickCount() - t)/cv::getTickFrequency();
fpsDlibHog = 1/tt_dlibHog;
putText(frame, format("DLIB HoG ; FPS = %.2f",fpsDlibHog), Point(10, 50), FONT_HERSHEY_SIMPLEX, 1.4, Scalar(0, 0, 255), 4);
imshow( "DLIB - HoG Face Detection", frame );
int k = waitKey(5);
if(k == 27)
{
destroyAllWindows();
break;
}
}
}
@@ -0,0 +1,70 @@
import cv2
import dlib
import time
import sys
def detectFaceDlibHog(detector, frame, inHeight=300, inWidth=0):
frameDlibHog = frame.copy()
frameHeight = frameDlibHog.shape[0]
frameWidth = frameDlibHog.shape[1]
if not inWidth:
inWidth = int((frameWidth / frameHeight)*inHeight)
scaleHeight = frameHeight / inHeight
scaleWidth = frameWidth / inWidth
frameDlibHogSmall = cv2.resize(frameDlibHog, (inWidth, inHeight))
faceRects = detector(frameDlibHogSmall, 0)
print(frameWidth, frameHeight, inWidth, inHeight)
bboxes = []
for faceRect in faceRects:
cvRect = [int(faceRect.left()*scaleWidth), int(faceRect.top()*scaleHeight),
int(faceRect.right()*scaleWidth), int(faceRect.bottom()*scaleHeight) ]
bboxes.append(cvRect)
cv2.rectangle(frameDlibHog, (cvRect[0], cvRect[1]), (cvRect[2], cvRect[3]), (0, 255, 0), round(frameHeight/150), 4)
return frameDlibHog, bboxes
if __name__ == "__main__" :
hogFaceDetector = dlib.get_frontal_face_detector()
source = 0
if len(sys.argv) > 1:
source = sys.argv[1]
cap = cv2.VideoCapture(source)
hasFrame, frame = cap.read()
vid_writer = cv2.VideoWriter('output-hog-{}.avi'.format(str(source).split(".")[0]),cv2.VideoWriter_fourcc('M','J','P','G'), 15, (frame.shape[1],frame.shape[0]))
frame_count = 0
tt_dlibHog = 0
while(1):
hasFrame, frame = cap.read()
if not hasFrame:
break
frame_count += 1
t = time.time()
outDlibHog, bboxes = detectFaceDlibHog(hogFaceDetector,frame)
tt_dlibHog += time.time() - t
fpsDlibHog = frame_count / tt_dlibHog
label = "DLIB HoG ; ; FPS : {:.2f}".format(fpsDlibHog)
cv2.putText(outDlibHog, label, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.4, (0, 0, 255), 3, cv2.LINE_AA)
cv2.imshow("Face Detection Comparison", outDlibHog)
vid_writer.write(outDlibHog)
if frame_count == 1:
tt_dlibHog = 0
k = cv2.waitKey(10)
if k == 27:
break
cv2.destroyAllWindows()
vid_writer.release()
@@ -0,0 +1,95 @@
#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <dlib/opencv.h>
#include <dlib/image_processing.h>
#include <dlib/dnn.h>
#include <dlib/data_io.h>
using namespace cv;
using namespace std;
using namespace dlib;
// Network Definition
/////////////////////////////////////////////////////////////////////////////////////////////////////
template <long num_filters, typename SUBNET> using con5d = con<num_filters,5,5,2,2,SUBNET>;
template <long num_filters, typename SUBNET> using con5 = con<num_filters,5,5,1,1,SUBNET>;
template <typename SUBNET> using downsampler = relu<affine<con5d<32, relu<affine<con5d<32, relu<affine<con5d<16,SUBNET>>>>>>>>>;
template <typename SUBNET> using rcon5 = relu<affine<con5<45,SUBNET>>>;
using net_type = loss_mmod<con<1,9,9,1,1,rcon5<rcon5<rcon5<downsampler<input_rgb_image_pyramid<pyramid_down<6>>>>>>>>;
/////////////////////////////////////////////////////////////////////////////////////////////////////
void detectFaceDlibMMOD(net_type mmodFaceDetector, Mat &frameDlibMmod, int inHeight=300, int inWidth=0)
{
int frameHeight = frameDlibMmod.rows;
int frameWidth = frameDlibMmod.cols;
if (!inWidth)
inWidth = (int)((frameWidth / (float)frameHeight) * inHeight);
float scaleHeight = frameHeight / (float)inHeight;
float scaleWidth = frameWidth / (float)inWidth;
Mat frameDlibMmodSmall;
resize(frameDlibMmod, frameDlibMmodSmall, Size(inWidth, inHeight));
// Convert OpenCV image format to Dlib's image format
cv_image<bgr_pixel> dlibIm(frameDlibMmodSmall);
matrix<rgb_pixel> dlibMatrix;
assign_image(dlibMatrix, dlibIm);
// Detect faces in the image
std::vector<dlib::mmod_rect> faceRects = mmodFaceDetector(dlibMatrix);
for ( size_t i = 0; i < faceRects.size(); i++ )
{
int x1 = (int)(faceRects[i].rect.left() * scaleWidth);
int y1 = (int)(faceRects[i].rect.top() * scaleHeight);
int x2 = (int)(faceRects[i].rect.right() * scaleWidth);
int y2 = (int)(faceRects[i].rect.bottom() * scaleHeight);
cv::rectangle(frameDlibMmod, Point(x1, y1), Point(x2, y2), Scalar(0,255,0), (int)(frameHeight/150.0), 4);
}
}
int main( int argc, const char** argv )
{
String mmodModelPath = "./mmod_human_face_detector.dat";
net_type mmodFaceDetector;
deserialize(mmodModelPath) >> mmodFaceDetector;
VideoCapture source;
if (argc == 1)
source.open(0);
else
source.open(argv[1]);
Mat frame;
double tt_dlibMmod = 0;
double fpsDlibMmod = 0;
while(1)
{
source >> frame;
if(frame.empty())
break;
double t = cv::getTickCount();
detectFaceDlibMMOD ( mmodFaceDetector, frame );
tt_dlibMmod = ((double)cv::getTickCount() - t)/cv::getTickFrequency();
fpsDlibMmod = 1/tt_dlibMmod;
putText(frame, format("DLIB MMOD ; FPS = %.2f",fpsDlibMmod), Point(10, 50), FONT_HERSHEY_SIMPLEX, 1.4, Scalar(0, 0, 255), 4);
imshow( "DLIB - MMOD Face Detection", frame );
int k = waitKey(5);
if(k == 27)
{
destroyAllWindows();
break;
}
}
}
@@ -0,0 +1,71 @@
import cv2
import dlib
import time
import sys
def detectFaceDlibMMOD(detector, frame, inHeight=300, inWidth=0):
frameDlibMMOD = frame.copy()
frameHeight = frameDlibMMOD.shape[0]
frameWidth = frameDlibMMOD.shape[1]
if not inWidth:
inWidth = int((frameWidth / frameHeight)*inHeight)
scaleHeight = frameHeight / inHeight
scaleWidth = frameWidth / inWidth
frameDlibMMODSmall = cv2.resize(frameDlibMMOD, (inWidth, inHeight))
faceRects = detector(frameDlibMMODSmall, 0)
print(frameWidth, frameHeight, inWidth, inHeight)
bboxes = []
for faceRect in faceRects:
cvRect = [int(faceRect.rect.left()*scaleWidth), int(faceRect.rect.top()*scaleHeight),
int(faceRect.rect.right()*scaleWidth), int(faceRect.rect.bottom()*scaleHeight) ]
bboxes.append(cvRect)
cv2.rectangle(frameDlibMMOD, (cvRect[0], cvRect[1]), (cvRect[2], cvRect[3]), (0, 255, 0), round(frameHeight/150), 4)
return frameDlibMMOD, bboxes
if __name__ == "__main__" :
source = 0
if len(sys.argv) > 1:
source = sys.argv[1]
cap = cv2.VideoCapture(source)
hasFrame, frame = cap.read()
dnnFaceDetector = dlib.cnn_face_detection_model_v1("./mmod_human_face_detector.dat")
vid_writer = cv2.VideoWriter('output-mmod-{}.avi'.format(str(source).split(".")[0]),cv2.VideoWriter_fourcc('M','J','P','G'), 15, (frame.shape[1],frame.shape[0]))
frame_count = 0
tt_dlibMmod = 0
while(1):
hasFrame, frame = cap.read()
if not hasFrame:
break
frame_count += 1
t = time.time()
outDlibMMOD, bboxes = detectFaceDlibMMOD(dnnFaceDetector,frame)
tt_dlibMmod += time.time() - t
fpsDlibMmod = frame_count / tt_dlibMmod
label = "DLIB MMOD ; FPS : {:.2f}".format(fpsDlibMmod)
cv2.putText(outDlibMMOD, label, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.4, (0, 0, 255), 3, cv2.LINE_AA)
cv2.imshow("Face Detection Comparison", outDlibMMOD)
vid_writer.write(outDlibMMOD)
if frame_count == 1:
tt_dlibMmod = 0
k = cv2.waitKey(10)
if k == 27:
break
cv2.destroyAllWindows()
vid_writer.release()
@@ -0,0 +1,96 @@
#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/dnn.hpp>
using namespace cv;
using namespace std;
using namespace cv::dnn;
const size_t inWidth = 300;
const size_t inHeight = 300;
const double inScaleFactor = 1.0;
const float confidenceThreshold = 0.7;
const cv::Scalar meanVal(104.0, 177.0, 123.0);
#define CAFFE
const std::string caffeConfigFile = "./deploy.prototxt";
const std::string caffeWeightFile = "./res10_300x300_ssd_iter_140000_fp16.caffemodel";
const std::string tensorflowConfigFile = "./opencv_face_detector.pbtxt";
const std::string tensorflowWeightFile = "./opencv_face_detector_uint8.pb";
void detectFaceOpenCVDNN(Net net, Mat &frameOpenCVDNN)
{
int frameHeight = frameOpenCVDNN.rows;
int frameWidth = frameOpenCVDNN.cols;
#ifdef CAFFE
cv::Mat inputBlob = cv::dnn::blobFromImage(frameOpenCVDNN, inScaleFactor, cv::Size(inWidth, inHeight), meanVal, false, false);
#else
cv::Mat inputBlob = cv::dnn::blobFromImage(frameOpenCVDNN, inScaleFactor, cv::Size(inWidth, inHeight), meanVal, true, false);
#endif
net.setInput(inputBlob, "data");
cv::Mat detection = net.forward("detection_out");
cv::Mat detectionMat(detection.size[2], detection.size[3], CV_32F, detection.ptr<float>());
for(int i = 0; i < detectionMat.rows; i++)
{
float confidence = detectionMat.at<float>(i, 2);
if(confidence > confidenceThreshold)
{
int x1 = static_cast<int>(detectionMat.at<float>(i, 3) * frameWidth);
int y1 = static_cast<int>(detectionMat.at<float>(i, 4) * frameHeight);
int x2 = static_cast<int>(detectionMat.at<float>(i, 5) * frameWidth);
int y2 = static_cast<int>(detectionMat.at<float>(i, 6) * frameHeight);
cv::rectangle(frameOpenCVDNN, cv::Point(x1, y1), cv::Point(x2, y2), cv::Scalar(0, 255, 0),2, 4);
}
}
}
int main( int argc, const char** argv )
{
#ifdef CAFFE
Net net = cv::dnn::readNetFromCaffe(caffeConfigFile, caffeWeightFile);
#else
Net net = cv::dnn::readNetFromTensorflow(tensorflowWeightFile, tensorflowConfigFile);
#endif
VideoCapture source;
if (argc == 1)
source.open(0);
else
source.open(argv[1]);
Mat frame;
double tt_opencvDNN = 0;
double fpsOpencvDNN = 0;
while(1)
{
source >> frame;
if(frame.empty())
break;
double t = cv::getTickCount();
detectFaceOpenCVDNN ( net, frame );
tt_opencvDNN = ((double)cv::getTickCount() - t)/cv::getTickFrequency();
fpsOpencvDNN = 1/tt_opencvDNN;
putText(frame, format("OpenCV DNN ; FPS = %.2f",fpsOpencvDNN), Point(10, 50), FONT_HERSHEY_SIMPLEX, 1.4, Scalar(0, 0, 255), 4);
imshow( "OpenCV - DNN Face Detection", frame );
int k = waitKey(5);
if(k == 27)
{
destroyAllWindows();
break;
}
}
}
@@ -0,0 +1,78 @@
import cv2
import time
import sys
def detectFaceOpenCVDnn(net, frame):
frameOpencvDnn = frame.copy()
frameHeight = frameOpencvDnn.shape[0]
frameWidth = frameOpencvDnn.shape[1]
blob = cv2.dnn.blobFromImage(frameOpencvDnn, 1.0, (300, 300), [104, 117, 123], False, False)
net.setInput(blob)
detections = net.forward()
bboxes = []
for i in range(detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > conf_threshold:
x1 = int(detections[0, 0, i, 3] * frameWidth)
y1 = int(detections[0, 0, i, 4] * frameHeight)
x2 = int(detections[0, 0, i, 5] * frameWidth)
y2 = int(detections[0, 0, i, 6] * frameHeight)
bboxes.append([x1, y1, x2, y2])
cv2.rectangle(frameOpencvDnn, (x1, y1), (x2, y2), (0, 255, 0), round(frameHeight/150), 8)
return frameOpencvDnn, bboxes
if __name__ == "__main__" :
# OpenCV DNN supports 2 networks.
# 1. FP16 version of the original caffe implementation ( 5.4 MB )
# 2. 8 bit Quantized version using Tensorflow ( 2.7 MB )
DNN = "TF"
if DNN == "CAFFE":
modelFile = "res10_300x300_ssd_iter_140000_fp16.caffemodel"
configFile = "deploy.prototxt"
net = cv2.dnn.readNetFromCaffe(configFile, modelFile)
else:
modelFile = "opencv_face_detector_uint8.pb"
configFile = "opencv_face_detector.pbtxt"
net = cv2.dnn.readNetFromTensorflow(modelFile, configFile)
conf_threshold = 0.7
source = 0
if len(sys.argv) > 1:
source = sys.argv[1]
cap = cv2.VideoCapture(source)
hasFrame, frame = cap.read()
vid_writer = cv2.VideoWriter('output-dnn-{}.avi'.format(str(source).split(".")[0]),cv2.VideoWriter_fourcc('M','J','P','G'), 15, (frame.shape[1],frame.shape[0]))
frame_count = 0
tt_opencvDnn = 0
while(1):
hasFrame, frame = cap.read()
if not hasFrame:
break
frame_count += 1
t = time.time()
outOpencvDnn, bboxes = detectFaceOpenCVDnn(net,frame)
tt_opencvDnn += time.time() - t
fpsOpencvDnn = frame_count / tt_opencvDnn
label = "OpenCV DNN ; FPS : {:.2f}".format(fpsOpencvDnn)
cv2.putText(outOpencvDnn, label, (10,50), cv2.FONT_HERSHEY_SIMPLEX, 1.4, (0, 0, 255), 3, cv2.LINE_AA)
cv2.imshow("Face Detection Comparison", outOpencvDnn)
vid_writer.write(outOpencvDnn)
if frame_count == 1:
tt_opencvDnn = 0
k = cv2.waitKey(10)
if k == 27:
break
cv2.destroyAllWindows()
vid_writer.release()
@@ -0,0 +1,77 @@
#include "opencv2/objdetect.hpp"
#include "opencv2/videoio.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <iostream>
#include <stdio.h>
using namespace std;
using namespace cv;
/** Global variables */
String faceCascadePath;
CascadeClassifier faceCascade;
void detectFaceOpenCVHaar(CascadeClassifier faceCascade, Mat &frameOpenCVHaar, int inHeight=300, int inWidth=0)
{
int frameHeight = frameOpenCVHaar.rows;
int frameWidth = frameOpenCVHaar.cols;
if (!inWidth)
inWidth = (int)((frameWidth / (float)frameHeight) * inHeight);
float scaleHeight = frameHeight / (float)inHeight;
float scaleWidth = frameWidth / (float)inWidth;
Mat frameOpenCVHaarSmall, frameGray;
resize(frameOpenCVHaar, frameOpenCVHaarSmall, Size(inWidth, inHeight));
cvtColor(frameOpenCVHaarSmall, frameGray, COLOR_BGR2GRAY);
std::vector<Rect> faces;
faceCascade.detectMultiScale(frameGray, faces);
for ( size_t i = 0; i < faces.size(); i++ )
{
int x1 = (int)(faces[i].x * scaleWidth);
int y1 = (int)(faces[i].y * scaleHeight);
int x2 = (int)((faces[i].x + faces[i].width) * scaleWidth);
int y2 = (int)((faces[i].y + faces[i].height) * scaleHeight);
rectangle(frameOpenCVHaar, Point(x1, y1), Point(x2, y2), Scalar(0,255,0), (int)(frameHeight/150.0), 4);
}
}
int main( int argc, const char** argv )
{
faceCascadePath = "./haarcascade_frontalface_default.xml";
if( !faceCascade.load( faceCascadePath ) ){ printf("--(!)Error loading face cascade\n"); return -1; };
VideoCapture source;
if (argc == 1)
source.open(0);
else
source.open(argv[1]);
Mat frame;
double tt_opencvHaar = 0;
double fpsOpencvHaar = 0;
while(1)
{
source >> frame;
if(frame.empty())
break;
double t = cv::getTickCount();
detectFaceOpenCVHaar ( faceCascade, frame );
tt_opencvHaar = ((double)cv::getTickCount() - t)/cv::getTickFrequency();
fpsOpencvHaar = 1/tt_opencvHaar;
putText(frame, format("OpenCV HAAR ; FPS = %.2f",fpsOpencvHaar), Point(10, 50), FONT_HERSHEY_SIMPLEX, 1.4, Scalar(0, 0, 255), 4);
imshow( "OpenCV - HAAR Face Detection", frame );
int k = waitKey(5);
if(k == 27)
{
destroyAllWindows();
break;
}
}
}
@@ -0,0 +1,72 @@
import cv2
import time
import sys
def detectFaceOpenCVHaar(faceCascade, frame, inHeight=300, inWidth=0):
frameOpenCVHaar = frame.copy()
frameHeight = frameOpenCVHaar.shape[0]
frameWidth = frameOpenCVHaar.shape[1]
if not inWidth:
inWidth = int((frameWidth / frameHeight) * inHeight)
scaleHeight = frameHeight / inHeight
scaleWidth = frameWidth / inWidth
frameOpenCVHaarSmall = cv2.resize(frameOpenCVHaar, (inWidth, inHeight))
frameGray = cv2.cvtColor(frameOpenCVHaarSmall, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(frameGray)
bboxes = []
for (x, y, w, h) in faces:
x1 = x
y1 = y
x2 = x + w
y2 = y + h
cvRect = [int(x1 * scaleWidth), int(y1 * scaleHeight),
int(x2 * scaleWidth), int(y2 * scaleHeight)]
bboxes.append(cvRect)
cv2.rectangle(frameOpenCVHaar, (cvRect[0], cvRect[1]), (cvRect[2], cvRect[3]), (0, 255, 0),
round(frameHeight / 150), 4)
return frameOpenCVHaar, bboxes
if __name__ == "__main__" :
source = 0
if len(sys.argv) > 1:
source = sys.argv[1]
faceCascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')
cap = cv2.VideoCapture(source)
hasFrame, frame = cap.read()
vid_writer = cv2.VideoWriter('output-haar-{}.avi'.format(str(source).split(".")[0]),cv2.VideoWriter_fourcc('M','J','P','G'), 15, (frame.shape[1],frame.shape[0]))
frame_count = 0
tt_opencvHaar = 0
while(1):
hasFrame, frame = cap.read()
if not hasFrame:
break
frame_count += 1
t = time.time()
outOpencvHaar, bboxes = detectFaceOpenCVHaar(faceCascade, frame)
tt_opencvHaar += time.time() - t
fpsOpencvHaar = frame_count / tt_opencvHaar
label = "OpenCV Haar ; FPS : {:.2f}".format(fpsOpencvHaar)
cv2.putText(outOpencvHaar, label, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.4, (0, 0, 255), 3, cv2.LINE_AA)
cv2.imshow("Face Detection Comparison", outOpencvHaar)
vid_writer.write(outOpencvHaar)
if frame_count == 1:
tt_opencvHaar = 0
k = cv2.waitKey(10)
if k == 27:
break
cv2.destroyAllWindows()
vid_writer.release()
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+264
View File
@@ -0,0 +1,264 @@
#include <iostream>
#include <string>
#include <vector>
#include <stdlib.h>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/objdetect.hpp>
#include <opencv2/videoio.hpp>
#include <opencv2/dnn.hpp>
#include <dlib/opencv.h>
#include <dlib/image_processing.h>
#include <dlib/dnn.h>
#include <dlib/data_io.h>
#include <dlib/image_processing/frontal_face_detector.h>
using namespace cv;
using namespace cv::dnn;
using namespace std;
using namespace dlib;
/** Global variables */
String faceCascadePath;
CascadeClassifier faceCascade;
void detectFaceOpenCVHaar(CascadeClassifier faceCascade, Mat &frameOpenCVHaar, int inHeight=300, int inWidth=0)
{
int frameHeight = frameOpenCVHaar.rows;
int frameWidth = frameOpenCVHaar.cols;
if (!inWidth)
inWidth = (int)((frameWidth / (float)frameHeight) * inHeight);
float scaleHeight = frameHeight / (float)inHeight;
float scaleWidth = frameWidth / (float)inWidth;
Mat frameOpenCVHaarSmall, frameGray;
resize(frameOpenCVHaar, frameOpenCVHaarSmall, Size(inWidth, inHeight));
cvtColor(frameOpenCVHaarSmall, frameGray, COLOR_BGR2GRAY);
std::vector<Rect> faces;
faceCascade.detectMultiScale(frameGray, faces);
for ( size_t i = 0; i < faces.size(); i++ )
{
int x1 = (int)(faces[i].x * scaleWidth);
int y1 = (int)(faces[i].y * scaleHeight);
int x2 = (int)((faces[i].x + faces[i].width) * scaleWidth);
int y2 = (int)((faces[i].y + faces[i].height) * scaleHeight);
cv::rectangle(frameOpenCVHaar, Point(x1, y1), Point(x2, y2), Scalar(0,255,0), (int)(frameHeight/150.0), 4);
}
}
const size_t inWidth = 300;
const size_t inHeight = 300;
const double inScaleFactor = 1.0;
const float confidenceThreshold = 0.7;
const cv::Scalar meanVal(104.0, 177.0, 123.0);
#define CAFFE
const std::string caffeConfigFile = "./deploy.prototxt";
const std::string caffeWeightFile = "./res10_300x300_ssd_iter_140000_fp16.caffemodel";
const std::string tensorflowConfigFile = "./opencv_face_detector.pbtxt";
const std::string tensorflowWeightFile = "./opencv_face_detector_uint8.pb";
void detectFaceOpenCVDNN(Net net, Mat &frameOpenCVDNN)
{
int frameHeight = frameOpenCVDNN.rows;
int frameWidth = frameOpenCVDNN.cols;
#ifdef CAFFE
cv::Mat inputBlob = cv::dnn::blobFromImage(frameOpenCVDNN, inScaleFactor, cv::Size(inWidth, inHeight), meanVal, false, false);
#else
cv::Mat inputBlob = cv::dnn::blobFromImage(frameOpenCVDNN, inScaleFactor, cv::Size(inWidth, inHeight), meanVal, true, false);
#endif
net.setInput(inputBlob, "data");
cv::Mat detection = net.forward("detection_out");
cv::Mat detectionMat(detection.size[2], detection.size[3], CV_32F, detection.ptr<float>());
for(int i = 0; i < detectionMat.rows; i++)
{
float confidence = detectionMat.at<float>(i, 2);
if(confidence > confidenceThreshold)
{
int x1 = static_cast<int>(detectionMat.at<float>(i, 3) * frameWidth);
int y1 = static_cast<int>(detectionMat.at<float>(i, 4) * frameHeight);
int x2 = static_cast<int>(detectionMat.at<float>(i, 5) * frameWidth);
int y2 = static_cast<int>(detectionMat.at<float>(i, 6) * frameHeight);
cv::rectangle(frameOpenCVDNN, cv::Point(x1, y1), cv::Point(x2, y2), cv::Scalar(0, 255, 0),(int)(frameHeight/150.0), 4);
}
}
}
void detectFaceDlibHog(frontal_face_detector hogFaceDetector, Mat &frameDlibHog, int inHeight=300, int inWidth=0)
{
int frameHeight = frameDlibHog.rows;
int frameWidth = frameDlibHog.cols;
if (!inWidth)
inWidth = (int)((frameWidth / (float)frameHeight) * inHeight);
float scaleHeight = frameHeight / (float)inHeight;
float scaleWidth = frameWidth / (float)inWidth;
Mat frameDlibHogSmall;
resize(frameDlibHog, frameDlibHogSmall, Size(inWidth, inHeight));
// Convert OpenCV image format to Dlib's image format
cv_image<bgr_pixel> dlibIm(frameDlibHogSmall);
// Detect faces in the image
std::vector<dlib::rectangle> faceRects = hogFaceDetector(dlibIm);
for ( size_t i = 0; i < faceRects.size(); i++ )
{
int x1 = (int)(faceRects[i].left() * scaleWidth);
int y1 = (int)(faceRects[i].top() * scaleHeight);
int x2 = (int)(faceRects[i].right() * scaleWidth);
int y2 = (int)(faceRects[i].bottom() * scaleHeight);
cv::rectangle(frameDlibHog, Point(x1, y1), Point(x2, y2), Scalar(0,255,0), (int)(frameHeight/150.0), 4);
}
}
// Network Definition
/////////////////////////////////////////////////////////////////////////////////////////////////////
template <long num_filters, typename SUBNET> using con5d = con<num_filters,5,5,2,2,SUBNET>;
template <long num_filters, typename SUBNET> using con5 = con<num_filters,5,5,1,1,SUBNET>;
template <typename SUBNET> using downsampler = relu<affine<con5d<32, relu<affine<con5d<32, relu<affine<con5d<16,SUBNET>>>>>>>>>;
template <typename SUBNET> using rcon5 = relu<affine<con5<45,SUBNET>>>;
using net_type = loss_mmod<con<1,9,9,1,1,rcon5<rcon5<rcon5<downsampler<input_rgb_image_pyramid<pyramid_down<6>>>>>>>>;
/////////////////////////////////////////////////////////////////////////////////////////////////////
void detectFaceDlibMMOD(net_type mmodFaceDetector, Mat &frameDlibMmod, int inHeight=300, int inWidth=0)
{
int frameHeight = frameDlibMmod.rows;
int frameWidth = frameDlibMmod.cols;
if (!inWidth)
inWidth = (int)((frameWidth / (float)frameHeight) * inHeight);
float scaleHeight = frameHeight / (float)inHeight;
float scaleWidth = frameWidth / (float)inWidth;
Mat frameDlibMmodSmall;
resize(frameDlibMmod, frameDlibMmodSmall, Size(inWidth, inHeight));
// Convert OpenCV image format to Dlib's image format
cv_image<bgr_pixel> dlibIm(frameDlibMmodSmall);
matrix<rgb_pixel> dlibMatrix;
assign_image(dlibMatrix, dlibIm);
// Detect faces in the image
std::vector<dlib::mmod_rect> faceRects = mmodFaceDetector(dlibMatrix);
for ( size_t i = 0; i < faceRects.size(); i++ )
{
int x1 = (int)(faceRects[i].rect.left() * scaleWidth);
int y1 = (int)(faceRects[i].rect.top() * scaleHeight);
int x2 = (int)(faceRects[i].rect.right() * scaleWidth);
int y2 = (int)(faceRects[i].rect.bottom() * scaleHeight);
cv::rectangle(frameDlibMmod, Point(x1, y1), Point(x2, y2), Scalar(0,255,0), (int)(frameHeight/150.0), 4);
}
}
int main( int argc, const char** argv )
{
faceCascadePath = "./haarcascade_frontalface_default.xml";
if( !faceCascade.load( faceCascadePath ) ){ printf("--(!)Error loading face cascade\n"); return -1; };
#ifdef CAFFE
Net net = cv::dnn::readNetFromCaffe(caffeConfigFile, caffeWeightFile);
#else
Net net = cv::dnn::readNetFromTensorflow(tensorflowWeightFile, tensorflowConfigFile);
#endif
frontal_face_detector hogFaceDetector = get_frontal_face_detector();
String mmodModelPath = "./mmod_human_face_detector.dat";
net_type mmodFaceDetector;
deserialize(mmodModelPath) >> mmodFaceDetector;
VideoCapture source;
if (argc == 1)
source.open(0);
else
source.open(argv[1]);
Mat frame;
int frame_count = 0;
double tt_opencvHaar = 0;
double tt_opencvDNN = 0;
double tt_dlibHog = 0;
double tt_dlibMmod = 0;
namedWindow("Face Detection Comparison", WINDOW_NORMAL);
double t = 0;
while(1)
{
source >> frame;
if(frame.empty())
break;
frame_count++;
t = cv::getTickCount();
Mat frameOpenCVHaar = frame.clone();
detectFaceOpenCVHaar ( faceCascade, frameOpenCVHaar );
tt_opencvHaar += ((double)cv::getTickCount() - t)/cv::getTickFrequency();
double fpsOpencvHaar = frame_count/tt_opencvHaar;
putText(frameOpenCVHaar, format("OpenCV HAAR ; FPS = %.2f",fpsOpencvHaar), Point(10, 50), FONT_HERSHEY_SIMPLEX, 1.4, Scalar(0, 0, 255), 4);
Mat frameOpenCVDNN = frame.clone();
t = cv::getTickCount();
detectFaceOpenCVDNN ( net, frameOpenCVDNN );
tt_opencvDNN += ((double)cv::getTickCount() - t)/cv::getTickFrequency();
double fpsOpencvDNN = frame_count/tt_opencvDNN;
putText(frameOpenCVDNN, format("OpenCV DNN ; FPS = %.2f",fpsOpencvDNN), Point(10, 50), FONT_HERSHEY_SIMPLEX, 1.4, Scalar(0, 0, 255), 4);
t = cv::getTickCount();
Mat frameDlibHog = frame.clone();
detectFaceDlibHog ( hogFaceDetector, frameDlibHog );
tt_dlibHog += ((double)cv::getTickCount() - t)/cv::getTickFrequency();
double fpsDlibHog = frame_count/tt_dlibHog;
putText(frameDlibHog, format("DLIB HoG ; FPS = %.2f",fpsDlibHog), Point(10, 50), FONT_HERSHEY_SIMPLEX, 1.4, Scalar(0, 0, 255), 4);
t = cv::getTickCount();
Mat frameDlibMmod = frame.clone();
detectFaceDlibMMOD ( mmodFaceDetector, frameDlibMmod );
tt_dlibMmod += ((double)cv::getTickCount() - t)/cv::getTickFrequency();
double fpsDlibMmod = frame_count/tt_dlibMmod;
putText(frameDlibMmod, format("DLIB MMOD ; FPS = %.2f",fpsDlibMmod), Point(10, 50), FONT_HERSHEY_SIMPLEX, 1.4, Scalar(0, 0, 255), 4);
Mat top, bottom, combined;
hconcat(frameOpenCVHaar, frameOpenCVDNN, top);
hconcat(frameDlibHog, frameDlibMmod, bottom);
vconcat(top, bottom, combined);
cv::resize(combined, combined, Size(), .5, .5);
imshow("Face Detection Comparison", combined );
int k = waitKey(5);
if(k == 27)
{
destroyAllWindows();
break;
}
if(frame_count == 1)
{
tt_opencvHaar = 0;
tt_opencvDNN = 0;
tt_dlibHog = 0;
tt_dlibMmod = 0;
}
}
}
+203
View File
@@ -0,0 +1,203 @@
import cv2
import dlib
import time
import sys
import numpy as np
# Model files
# OpenCV HAAR
faceCascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')
#OpenCV DNN supports 2 networks.
# 1. FP16 version of the original caffe implementation ( 5.4 MB )
# 2. 8 bit Quantized version using Tensorflow ( 2.7 MB )
DNN = "TF"
if DNN=="CAFFE":
modelFile = "res10_300x300_ssd_iter_140000_fp16.caffemodel"
configFile = "deploy.prototxt"
net = cv2.dnn.readNetFromCaffe(configFile, modelFile)
else:
modelFile = "opencv_face_detector_uint8.pb"
configFile = "opencv_face_detector.pbtxt"
net = cv2.dnn.readNetFromTensorflow(modelFile, configFile)
conf_threshold = 0.7
# DLIB HoG
hogFaceDetector = dlib.get_frontal_face_detector()
# DLIB MMOD
dnnFaceDetector = dlib.cnn_face_detection_model_v1("./mmod_human_face_detector.dat")
def detectFaceOpenCVHaar(faceCascade, frame, inHeight=300, inWidth=0):
frameOpenCVHaar = frame.copy()
frameHeight = frameOpenCVHaar.shape[0]
frameWidth = frameOpenCVHaar.shape[1]
if not inWidth:
inWidth = int((frameWidth / frameHeight) * inHeight)
scaleHeight = frameHeight / inHeight
scaleWidth = frameWidth / inWidth
frameOpenCVHaarSmall = cv2.resize(frameOpenCVHaar, (inWidth, inHeight))
frameGray = cv2.cvtColor(frameOpenCVHaarSmall, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(frameGray)
bboxes = []
for (x, y, w, h) in faces:
x1 = x
y1 = y
x2 = x + w
y2 = y + h
cvRect = [int(x1 * scaleWidth), int(y1 * scaleHeight),
int(x2 * scaleWidth), int(y2 * scaleHeight)]
bboxes.append(cvRect)
cv2.rectangle(frameOpenCVHaar, (cvRect[0], cvRect[1]), (cvRect[2], cvRect[3]), (0, 255, 0),
round(frameHeight / 150), 4)
return frameOpenCVHaar, bboxes
def detectFaceOpenCVDnn(net, frame):
frameOpencvDnn = frame.copy()
frameHeight = frameOpencvDnn.shape[0]
frameWidth = frameOpencvDnn.shape[1]
blob = cv2.dnn.blobFromImage(frameOpencvDnn, 1.0, (300, 300), [104, 117, 123], False, False)
net.setInput(blob)
detections = net.forward()
bboxes = []
for i in range(detections.shape[2]):
confidence = detections[0, 0, i, 2]
if confidence > conf_threshold:
x1 = int(detections[0, 0, i, 3] * frameWidth)
y1 = int(detections[0, 0, i, 4] * frameHeight)
x2 = int(detections[0, 0, i, 5] * frameWidth)
y2 = int(detections[0, 0, i, 6] * frameHeight)
bboxes.append([x1, y1, x2, y2])
cv2.rectangle(frameOpencvDnn, (x1, y1), (x2, y2), (0, 255, 0), round(frameHeight/150), 8)
return frameOpencvDnn, bboxes
def detectFaceDlibHog(detector, frame, inHeight=300, inWidth=0):
frameDlibHog = frame.copy()
frameHeight = frameDlibHog.shape[0]
frameWidth = frameDlibHog.shape[1]
if not inWidth:
inWidth = int((frameWidth / frameHeight)*inHeight)
scaleHeight = frameHeight / inHeight
scaleWidth = frameWidth / inWidth
frameDlibHogSmall = cv2.resize(frameDlibHog, (inWidth, inHeight))
faceRects = detector(frameDlibHogSmall, 0)
print(frameWidth, frameHeight, inWidth, inHeight)
bboxes = []
for faceRect in faceRects:
cvRect = [int(faceRect.left()*scaleWidth), int(faceRect.top()*scaleHeight),
int(faceRect.right()*scaleWidth), int(faceRect.bottom()*scaleHeight) ]
bboxes.append(cvRect)
cv2.rectangle(frameDlibHog, (cvRect[0], cvRect[1]), (cvRect[2], cvRect[3]), (0, 255, 0), round(frameHeight/150), 4)
return frameDlibHog, bboxes
def detectFaceDlibMMOD(detector, frame, inHeight=300, inWidth=0):
frameDlibMMOD = frame.copy()
frameHeight = frameDlibMMOD.shape[0]
frameWidth = frameDlibMMOD.shape[1]
if not inWidth:
inWidth = int((frameWidth / frameHeight)*inHeight)
scaleHeight = frameHeight / inHeight
scaleWidth = frameWidth / inWidth
frameDlibMMODSmall = cv2.resize(frameDlibMMOD, (inWidth, inHeight))
faceRects = detector(frameDlibMMODSmall, 0)
print(frameWidth, frameHeight, inWidth, inHeight)
bboxes = []
for faceRect in faceRects:
cvRect = [int(faceRect.rect.left()*scaleWidth), int(faceRect.rect.top()*scaleHeight),
int(faceRect.rect.right()*scaleWidth), int(faceRect.rect.bottom()*scaleHeight) ]
bboxes.append(cvRect)
cv2.rectangle(frameDlibMMOD, (cvRect[0], cvRect[1]), (cvRect[2], cvRect[3]), (0, 255, 0), round(frameHeight/150), 4)
return frameDlibMMOD, bboxes
source = 0
if len(sys.argv) > 1:
source = sys.argv[1]
cap = cv2.VideoCapture(source)
hasFrame, frame = cap.read()
cv2.namedWindow("Face Detection Comparison", cv2.WINDOW_NORMAL)
vid_writer = cv2.VideoWriter('output-{}.avi'.format(str(source).split(".")[0]),cv2.VideoWriter_fourcc('M','J','P','G'), 15, (frame.shape[1]*2,frame.shape[0]*2))
frame_count = 0
tt_opencvHaar = 0
tt_opencvDnn = 0
tt_dlibHog = 0
tt_dlibMmod = 0
while(1):
hasFrame, frame = cap.read()
if not hasFrame:
break
frame_count += 1
t = time.time()
outOpencvHaar, bboxes = detectFaceOpenCVHaar(faceCascade, frame)
tt_opencvHaar += time.time() - t
fpsOpencvHaar = frame_count / tt_opencvHaar
label = "OpenCV Haar ; FPS : {:.2f}".format(fpsOpencvHaar)
cv2.putText(outOpencvHaar, label, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.4, (0, 0, 255), 3, cv2.LINE_AA)
t = time.time()
outOpencvDnn, bboxes = detectFaceOpenCVDnn(net,frame)
tt_opencvDnn += time.time() - t
fpsOpencvDnn = frame_count / tt_opencvDnn
label = "OpenCV DNN ; FPS : {:.2f}".format(fpsOpencvDnn)
cv2.putText(outOpencvDnn, label, (10,50), cv2.FONT_HERSHEY_SIMPLEX, 1.4, (0, 0, 255), 3, cv2.LINE_AA)
t = time.time()
outDlibHog, bboxes = detectFaceDlibHog(hogFaceDetector,frame)
tt_dlibHog += time.time() - t
fpsDlibHog = frame_count / tt_dlibHog
label = "DLIB HoG ; ; FPS : {:.2f}".format(fpsDlibHog)
cv2.putText(outDlibHog, label, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.4, (0, 0, 255), 3, cv2.LINE_AA)
t = time.time()
outDlibMMOD, bboxes = detectFaceDlibMMOD(dnnFaceDetector,frame)
tt_dlibMmod += time.time() - t
fpsDlibMmod = frame_count / tt_dlibMmod
label = "DLIB MMOD ; FPS : {:.2f}".format(fpsDlibMmod)
cv2.putText(outDlibMMOD, label, (10, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.4, (0, 0, 255), 3, cv2.LINE_AA)
top = np.hstack([outOpencvHaar, outOpencvDnn])
bottom = np.hstack([outDlibHog, outDlibMMOD])
combined = np.vstack([top, bottom])
cv2.imshow("Face Detection Comparison", combined)
if frame_count == 1:
tt_opencvHaar = 0
tt_opencvDnn = 0
tt_dlibHog = 0
tt_dlibMmod = 0
vid_writer.write(combined)
k = cv2.waitKey(10)
if k == 27:
break
cv2.destroyAllWindows()
vid_writer.release()
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -2,7 +2,7 @@ import cv2
import time
import numpy as np
MODE = "MPI"
MODE = "COCO"
if MODE is "COCO":
protoFile = "pose/coco/pose_deploy_linevec.prototxt"