1、安装OpenCV
我参考的下方这个链接安装的OpenCV4.5.3
【精选】【CUDA加速DNN】【CSI摄像头】Jetson nano使用记录之源代码编译安装opencv4.5.1_jetson nano编译opencv4_絮沫的博客-CSDN博客
安装之后jtop显示支持CUDA。
2、写代码验证
写了一个人脸检测的程序,验证GPU使用情况。
代码如下:
#include <iostream>
#include <string>
#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/objdetect.hpp>
#include <opencv2/imgproc/types_c.h>
#include <opencv2/videoio.hpp>
#include <opencv2/cudaobjdetect.hpp>
#include <opencv2/cudaimgproc.hpp>
using namespace std;
using namespace cv;
int main( int argc, char** argv )
{
// Initialize OpenCV with CUDA support
cv::cuda::setDevice(0); // Use the first CUDA device
cv::cuda::printCudaDeviceInfo(0);
VideoCapture cap(1);
//创建显示窗口
namedWindow("faceWithCUDA", WINDOW_AUTOSIZE);
cv::Mat img;
cv::cuda::GpuMat gpuImg, gpuImgGray;
cv::cuda::GpuMat objbuf;
cv::Ptr<cv::cuda::CascadeClassifier> faceCascade = cv::cuda::CascadeClassifier::create("/home/tuotuo/opencv-4.5.3/data/haarcascades_cuda/haarcascade_frontalface_alt.xml");
//逐帧显示
while(true)
{
cap >> img;
gpuImg.upload(img);
cv::cuda::cvtColor(gpuImg, gpuImgGray, cv::COLOR_BGR2GRAY);
faceCascade->detectMultiScale(gpuImgGray, objbuf);
std::vector<cv::Rect> faces;
faceCascade->convert(objbuf, faces);
for (int i = 0; i < faces.size(); i++)
{
cv::rectangle(img, faces[i], cv::Scalar(255, 0, 0), 2);
}
imshow("faceWithCUDA",img);
int keycode = cv::waitKey(30) & 0xff ; //ESC键退出
if (keycode == 27) break ;
}
cap.release();
destroyAllWindows() ;
}
运行,jtop查看GPU使用情况,GPU拉满。