01
人脸检测源码
从码云OpenCV学堂上获取源码,打开给大家看看,源码是这样的
代码语言:javascript复制#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char** argv) {
dnn::Net net = dnn::readNetFromTensorflow("opencv_face_detector_uint8.pb", "opencv_face_detector.pbtxt");
net.setPreferableBackend(cv::dnn::DNN_BACKEND_CUDA);
net.setPreferableTarget(cv::dnn::DNN_TARGET_CUDA);
VideoCapture capture("example_dsh.mp4");
Mat frame;
while (true) {
capture.read(frame);
if (frame.empty()) {
break;
}
// HWC - NCHW
Mat blob = dnn::blobFromImage(frame, 1.0, Size(300, 300), Scalar(104, 177, 123), false, false);
net.setInput(blob);// NCHW
Mat probs = net.forward(); // 1x1xNx7
Mat detectionMat(probs.size[2], probs.size[3], CV_32F, probs.ptr<float>());
// 解析结果
for (int i = 0; i < detectionMat.rows; i ) {
float confidence = detectionMat.at<float>(i, 2);
if (confidence > 0.5) {
int x1 = static_cast<int>(detectionMat.at<float>(i, 3)*frame.cols);
int y1 = static_cast<int>(detectionMat.at<float>(i, 4)*frame.rows);
int x2 = static_cast<int>(detectionMat.at<float>(i, 5)*frame.cols);
int y2 = static_cast<int>(detectionMat.at<float>(i, 6)*frame.rows);
Rect box(x1, y1, x2 - x1, y2 - y1);
rectangle(frame, box, Scalar(0, 0, 255), 2, 8, 0);
}
}
imshow("Jetson Nano OpenCV4.5.4 DNN C Demo", frame);
int c = waitKey(1);
if (c == 27) { //
break;
}
}
return 0;
}
02
生成CMakeLists.txt
做一个CMakeLists.txt文件,内容如下,自己看看,注意一下,我的OpenCV4.5.4版本是我重新编译,支持CUDA的版本。cmake直接编译吧
你好
代码语言:javascript复制cmake_minimum_required( VERSION 2.8 )
# 声明一个 cmake 工程
project(face_detect_demo)
# 设置编译模式
#set( CMAKE_BUILD_TYPE "Debug" )
#添加OPENCV库
#指定OpenCV版本,代码如下
#find_package(OpenCV 4.5.4 REQUIRED)
#如果不需要指定OpenCV版本,代码如下
find_package(OpenCV REQUIRED)
include_directories(
./src/)
#添加OpenCV头文件
include_directories(${OpenCV_INCLUDE_DIRS})
#显示OpenCV_INCLUDE_DIRS的值
message(${OpenCV_INCLUDE_DIRS})
FILE(GLOB_RECURSE TEST_SRC
src/*.cpp
#src/*.c
#${CMAKE_SOURCE_DIR}/*.cpp
#${CMAKE_SOURCE_DIR}/*.cp
)
# 添加一个可执行程序
# 语法:add_executable( 程序名 源代码文件 )
add_executable(target faceApp.cpp ${TEST_SRC})
# 将库文件链接到可执行程序上
target_link_libraries(target ${OpenCV_LIBS})
03
make生成可执行文件
cmake已经成功了,现在再make一下,生成可执行文件吧,我们的可执行文件名称是target,之前定义在CMakeLists.txt文件中,make也成功了,真不错!
04
运行测试
直接运行可执行文件,扫安毋躁,真的可以啦,OpenCV C 代码成功运行在Jetson Nano上了,从此以后我再也不说OpenCV C 快速入门30讲不能移植到嵌入式上跑了。