怎么调用yolo在opencv中用C++识别两张图片不同之处
时间: 2024-03-14 19:45:32 浏览: 26
要在OpenCV中使用YOLO进行图像检测,可以按照以下步骤进行:
1. 安装OpenCV和YOLO
2. 加载YOLO网络和权重文件,初始化检测器
```cpp
cv::dnn::Net net = cv::dnn::readNetFromDarknet(yolo_cfg_path, yolo_weights_path);
```
3. 读取图像,将其转换为blob格式并传递给网络进行检测
```cpp
cv::Mat image = cv::imread(image_path);
cv::Mat blob = cv::dnn::blobFromImage(image, 1 / 255.0, cv::Size(416, 416), cv::Scalar(0, 0, 0), true, false);
net.setInput(blob);
cv::Mat detection = net.forward();
```
4. 解析检测结果并绘制边界框
```cpp
float confidence_threshold = 0.5;
std::vector<int> class_ids;
std::vector<float> confidences;
std::vector<cv::Rect> boxes;
for (int i = 0; i < detection.rows; ++i) {
cv::Mat row = detection.row(i);
cv::Mat scores = row.colRange(5, detection.cols);
cv::Point class_id;
double confidence;
cv::minMaxLoc(scores, nullptr, &confidence, nullptr, &class_id);
if (confidence > confidence_threshold) {
int x_center = static_cast<int>(row.at<float>(0) * image.cols);
int y_center = static_cast<int>(row.at<float>(1) * image.rows);
int width = static_cast<int>(row.at<float>(2) * image.cols);
int height = static_cast<int>(row.at<float>(3) * image.rows);
int x_left = x_center - width / 2;
int y_top = y_center - height / 2;
class_ids.push_back(class_id.x);
confidences.push_back(confidence);
boxes.emplace_back(x_left, y_top, width, height);
}
}
for (int i = 0; i < boxes.size(); ++i) {
cv::rectangle(image, boxes[i], cv::Scalar(0, 0, 255), 2);
}
```
要识别两张图片不同之处,可以将两张图片都传递给YOLO进行检测,然后比较检测结果的差异。可以使用OpenCV的图像差分函数(cv::absdiff)来比较两张图像的像素值差异,并将差异区域作为输入传递给YOLO进行检测,然后在原始图像上绘制检测结果的边界框。