【发布时间】:2018-12-17 10:01:57
【问题描述】:
我正在尝试编写一个简单的人脸检测算法,使用 OpenCV 进行相机捕捉,使用 Dlib 进行人脸检测(使用定向梯度直方图算法)。
使用 Python,我以大约 20 fps 的速度获得了不错的性能。 但是,C++ 中相同的代码性能很差,每个 dlib 的检测过程大约需要 4 秒。
有人知道发生了什么吗?
我做了一些优化,但并没有真正提高性能:
- 图像缩小到 640x480
- 我在启用 AVX 指令的情况下编译了 dlib
- 我还尝试使用 -0fast 标志进行编译...
感谢您的帮助。
编辑:找到解决方案!通过使用此消息末尾的命令进行编译,我设法在 C++ 下达到了类似的良好性能。在此之前,我使用了 Jetbrain 的 CLion IDE 中的编译器,但它无法正常工作,即使编译器发送了肯定的“AVX 指令已启用”消息。 AVX Instructions 是我的问题的答案。
代码如下:
在 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()
对于 C++ 编译,我使用 cmake,这是我的 CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(FaceDetection)
set(CMAKE_CXX_STANDARD 14)
set(GCC_COVERAGE_COMPILE_FLAGS " -Ofast")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${GCC_COVERAGE_COMPILE_FLAGS}" )
add_subdirectory(/path/to/dlib/dlib-19.14/dlib dlib_build)
find_package( OpenCV REQUIRED)
add_executable(FaceDetection main.cpp)
target_link_libraries( FaceDetection ${OpenCV_LIBS} dlib::dlib)
我使用以下命令运行编译:
cmake . -DUSE_AVX_INSTRUCTIONS=ON
cmake --build . --config Release
【问题讨论】:
-
你是如何编译你的代码的?是否启用了编译器优化?
-
你有 Visual Studio 吗? (我认为您需要完整的 MSDN 版本,而不是社区版)。如果是这样,它有一个出色的分析器。
-
我没有 Visual Studio,我在 Linux 上(基于 Ubuntu 18.04 的 Linux Mint),我看到了 Visual Studio 的 Linux 版本,它是否带有分析器?我在帖子中添加了我的编译选项。
-
找到解决方案! CLion IDE 没有正确处理编译选项(或者我可能没有正确使用它),在 IDE 外部编译效果很好。
-
@JérômeBruzaud 因此,您不应将 SOLVED 添加到问题的标题或类似内容中,您应该发布答案并将其标记为正确。