python - Dlib 人脸检测在 C++ 上表现糟糕,在 Python 上表现不错,为什么?

标签 python c++ dlib

我正在尝试编写一个简单的人脸检测算法,使用 OpenCV 进行相机捕获,使用 Dlib 进行人脸检测(使用定向梯度直方图算法)。

使用 Python,我获得了大约 20 fps 的不错性能。 然而,C++ 中的相同代码性能非常差,每个 dlib 的检测过程大约需要 4 秒。

有人知道发生了什么吗?

我做了一些优化,但没有真正提高性能:

  • 图片缩小到 640x480
  • 我在启用 AVX 指令的情况下编译了 dlib
  • 我还尝试使用 -0fast 标志进行编译...

代码如下:

在 C++ 中:

#include "opencv2/objdetect.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/imgproc.hpp"
#include <dlib/opencv.h>
#include <dlib/image_processing/frontal_face_detector.h>
#include <dlib/image_processing.h>

using namespace dlib;
using namespace std;

int main(){

cv::VideoCapture cap(0);
vector<cv::Rect> facesCV;
vector<rectangle> faces;
frontal_face_detector detector = get_frontal_face_detector();
cv::namedWindow("test");
cv::Mat frame, small;

if (!cap.isOpened()) {
    cerr << "Unable to connect to camera" << endl;
    return 1;
}

while (true) {
    // Grab a frame
    if (!cap.read(frame)) {
        break;
    }
    cv::resize(frame, small, {640, 480});
    cv_image<rgb_pixel> cimg(small);

    // Detect faces
    faces = detector(cimg);
    for (auto &f : faces) {
        facesCV.emplace_back(cv::Point((int) f.left(), (int) f.top()), cv::Point((int) f.right(), (int) f.bottom()));
    }

    for (auto &r : facesCV) {
        cv::rectangle(small, r, {0, 255, 0}, 2);
    }
    cv::imshow("test", small);
    cv::waitKey(1);
    faces.clear();
    facesCV.clear();
}
}

在 Python 中:

import argparse
import cv2
import dlib

#initialize face detector
detector = dlib.get_frontal_face_detector()

#initialize video source
cam = cv2.VideoCapture(0)
window = cv2.namedWindow("camera")

while True:
    ret, image = cam.read()
    if ret is True:
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        gray =cv2.resize(gray, (640, 480))

        for r in detector(gray, 0):
            cv2.rectangle(image, (r.left(), r.top()), (r.right(), r.bottom()), (0, 255, 0), 2)

        cv2.imshow(window, image)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    else:
        break

cam.release()
cv2.destroyAllWindows()

最佳答案

问题来自 CMakeLists.txt。需要以这种方式在 CMakeLists.txt 中设置 AVX 优化:

set(USE_AVX_INSTRUCTIONS ON CACHE BOOL "Use AVX instructions")
add_subdirectory("path/to/dlib" dlib_build)

add_executable(myProject main.cpp)
target_link_libraries( myProject dlib::dlib)

关于python - Dlib 人脸检测在 C++ 上表现糟糕,在 Python 上表现不错,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51250296/

相关文章:

c++ - 类似函数的宏和奇怪的行为

c++ - dlib 的 dcd trainer 的 'warm start' 选项是否只用于 1 类分类?

python - 字符串格式化,从右而不是左修剪

python - Django + Heroku 数据库

c++ - 在 C++ 中,如何修改运算符以便在同一条语句中连续调用它两次?

c++ - 为什么 MFC DoModal 返回 -1 ? -1 是什么意思?

python-3.x - 如何在 digital ocean 上的 Ubuntu VPS 上安装 dlib

python - 使用pip安装Dlib时出现错误

python - OpenCV:从 VideoCapture 读取帧将视频推进到奇怪的错误位置

python - 如何在Python中的第二个字符匹配上分割字符串?