C++ opencv深度学习
时间: 2023-12-11 13:33:13 浏览: 123
OpenCV深度学习
C++ Opencv是一个开源计算机视觉库,它包含了很多计算机视觉和机器学习的经典算法,如图像处理、特征检测、目标检测、人脸识别等。同时,Opencv也支持深度学习,可以用于图像分类、目标检测、语义分割等任务。以下是一些C++ Opencv深度学习的例子:
1. 使用Opencv进行图像分类
```c++
#include <opencv2/opencv.hpp>
#include <opencv2/dnn.hpp>
#include <iostream>
using namespace cv;
using namespace cv::dnn;
using namespace std;
int main()
{
// 加载模型和标签
Net net = readNetFromCaffe("deploy.prototxt", "model.caffemodel");
string label[10] = {"airplane", "automobile", "bird", "cat", "deer", "dog", "frog", "horse", "ship", "truck"};
// 加载图像
Mat img = imread("test.jpg");
// 图像预处理
Mat inputBlob = blobFromImage(img, 1.0, Size(32, 32), Scalar(104, 117, 123), false, false);
// 输入模型进行预测
net.setInput(inputBlob, "data");
Mat prob = net.forward("prob");
// 输出预测结果
Point classIdPoint;
double confidence;
minMaxLoc(prob.reshape(1, 1), 0, &confidence, 0, &classIdPoint);
int classId = classIdPoint.x;
cout << "Predicted class: " << label[classId] << endl;
cout << "Confidence: " << confidence << endl;
return 0;
}
```
2. 使用Opencv进行目标检测
```c++
#include <opencv2/opencv.hpp>
#include <opencv2/dnn.hpp>
#include <iostream>
using namespace cv;
using namespace cv::dnn;
using namespace std;
int main()
{
// 加载模型和标签
Net net = readNetFromCaffe("deploy.prototxt", "model.caffemodel");
string label[21] = {"background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"};
// 加载图像
Mat img = imread("test.jpg");
// 图像预处理
Mat inputBlob = blobFromImage(img, 0.007843, Size(300, 300), Scalar(127.5, 127.5, 127.5), false, false);
// 输入模型进行预测
net.setInput(inputBlob, "data");
Mat detection = net.forward("detection_out");
// 输出预测结果
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 > 0.5)
{
int classId = (int)(detectionMat.at<float>(i, 1));
int left = (int)(detectionMat.at<float>(i, 3) * img.cols);
int top = (int)(detectionMat.at<float>(i, 4) * img.rows);
int right = (int)(detectionMat.at<float>(i, 5) * img.cols);
int bottom = (int)(detectionMat.at<float>(i, 6) * img.rows);
rectangle(img, Point(left, top), Point(right, bottom), Scalar(0, 255, 0), 2);
putText(img, label[classId], Point(left, top - 5), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(0, 255, 0), 2);
}
}
// 显示结果
imshow("result", img);
waitKey(0);
return 0;
}
```
阅读全文