学习openCV,需要动态监测视频中的光斑,并绘制轮廓
openCV中的二值化,可以过滤出较大块的高亮区域,测试代码中使用灰度阈值230-255之间来获取
并将其轮廓获取,求出轮廓的大小面积,并求拟合椭圆,从而得出光斑的位置和中心,具体实现代码和效果如下:
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/calib3d/calib3d.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
Mat process(Mat& srcImg)
{
Mat dstImg = srcImg.clone();
Mat tempImg = srcImg.clone();
cvtColor(tempImg, tempImg, CV_BGR2GRAY);//色域转换
GaussianBlur(tempImg, tempImg, Size(3, 3), 0, 0);//高斯滤波
threshold(tempImg, tempImg, 230, 255, CV_THRESH_BINARY);//二值化
std::vector<std::vector<Point>> contours;
std::vector<Vec4i> hierarcy;
findContours(tempImg, contours, hierarcy, CV_RETR_TREE, CV_CHAIN_APPROX_NONE);//取轮廓
std::vector<RotatedRect> box(contours.size());
int max_index = 0;
float max_area = 0;
for (int i = 0; i < contours.size(); i++)//求拟合椭圆
{
if (contours[i].size() >= 50)
{
box[i] = fitEllipse(Mat(contours[i]));
Size2f size = box[i].size;
if (size.height > 15 && size.width > 15 && size.height*size.width > max_area)
{
max_area = size.height*size.width;
max_index = i;
}
}
}
if (max_area != 0)//绘制中心十字
{
Point2d center = box[max_index].center;
line(dstImg, Point2f(center.x, center.y - 6), Point2f(center.x, center.y + 6), Scalar(0, 0, 255), 2, 8);
line(dstImg, Point2f(center.x - 6, center.y), Point2f(center.x + 6, center.y), Scalar(0, 0, 255), 2, 8);
ellipse(dstImg, box[max_index], Scalar(0, 255, 0), 1, 8);
}
return dstImg;
}
int main()
{
VideoCapture camera(0);
if (!camera.isOpened())
{
std::cout << "打开摄像头失败" << std::endl;
return -1;
}
Mat cache;
while (true)
{
camera.read(cache);
imshow("test", process(cache));
waitKey(20);
}
return 0;
}
实现效果如下(偷个懒,这个光斑就用家里的灯来模拟了hhh)
如果对您有帮助的话,麻烦给作者来个小小的👍,谢谢啦