opencvc++框出装甲板
时间: 2023-11-27 17:47:47 浏览: 140
以下是使用OpenCV C++框出装甲板的示例代码:
```cpp
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
// 打开视频文件
VideoCapture cap("/home/geek_style/桌面/ood_red.mp4"); if (!cap.isOpened())
{
cout << "Error opening video file" << endl;
return -1;
}
// 定义变量
Mat frame, channels[3], binary, Gaussian, dilate;
Mat element = getStructuringElement(MORPH_RECT, Size(5, 5));
Rect boundRect; RotatedRect box;
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
vector<Point2f> boxPts(4);
while (true)
{
// 读取视频帧
cap >> frame;
if (frame.empty())
{
break;
}
// 预处理图像
split(frame, channels);
subtract(channels[2], channels[0], binary);
threshold(binary, binary, 0, 255, THRESH_OTSU);
GaussianBlur(binary, Gaussian, Size(3, 3), 0, 0);
dilate(Gaussian, dilate, element);
// 查找轮廓
findContours(dilate, contours, hierarchy, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);
// 遍历轮廓
for (size_t i = 0; i < contours.size(); i++)
{
// 计算轮廓的最小外接矩形
box = minAreaRect(contours[i]);
box.points(boxPts.data());
// 计算矩形的长宽比
float width = box.size.width;
float height = box.size.height;
float ratio = max(width, height) / min(width, height);
// 如果长宽比符合要求,则框出矩形
if (ratio > 1.5 && ratio < 3.5)
{
boundRect = boundingRect(contours[i]);
rectangle(frame, boundRect, Scalar(0, 255, 0), 2);
}
}
// 显示结果
imshow("frame", frame);
if (waitKey(30) == 27)
{
break;
}
}
return 0;
}
```
阅读全文