基于opencv、c++,请写出一份基于轮廓形状的视频图片模板匹配代码。依照模板图片物品的形状,来匹配视频中可能出现的对应物品。
时间: 2024-04-15 14:27:45 浏览: 58
当然,下面是一份基于轮廓形状的视频图片模板匹配代码,使用OpenCV和C++编写:
```cpp
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
// 读取模板图片
Mat templateImage = imread("template.png", IMREAD_GRAYSCALE);
if (templateImage.empty())
{
cout << "无法读取模板图片!" << endl;
return -1;
}
// 创建窗口
namedWindow("模板匹配", WINDOW_NORMAL);
// 打开视频文件
VideoCapture cap("video.mp4");
if (!cap.isOpened())
{
cout << "无法打开视频文件!" << endl;
return -1;
}
Mat frame, grayFrame;
while (cap.read(frame))
{
// 将当前帧转换为灰度图像
cvtColor(frame, grayFrame, COLOR_BGR2GRAY);
// 进行模板匹配
Mat result;
matchTemplate(grayFrame, templateImage, result, TM_CCOEFF_NORMED);
// 设置匹配阈值
double threshold = 0.8;
threshold = threshold * 255;
// 寻找匹配位置
vector<Point> locations;
for (int y = 0; y < result.rows; y++)
{
for (int x = 0; x < result.cols; x++)
{
if (result.at<float>(y, x) >= threshold)
{
locations.push_back(Point(x, y));
}
}
}
// 绘制矩形框标记匹配位置
for (const Point& location : locations)
{
rectangle(frame, location, Point(location.x + templateImage.cols, location.y + templateImage.rows), Scalar(0, 255, 0), 2);
}
// 显示结果
imshow("模板匹配", frame);
// 按下ESC键退出
if (waitKey(1) == 27)
{
break;
}
}
// 释放资源
cap.release();
destroyAllWindows();
return 0;
}
```
请将模板图片保存为`template.png`,视频文件保存为`video.mp4`,然后使用C++编译器编译运行此代码。代码中的模板匹配方法使用了`TM_CCOEFF_NORMED`算法,你可以根据实际需求选择其他算法。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)