Opencv摄像头实时捕捉小程序
先上一个好玩的动图看看结果:
驱动摄像头
首先先驱动摄像头
实现的代码如下:
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
int main()
{
Mat img_src;
VideoCapture cam(0);
while(1)
{
cam >>img_src;
imshow("camera",img_src);
char c=(char)waitKey(30);
if (c==27)
{
break;
}
}
return 0;
}
没问题的话此处应该会打开你的摄像头,你可以看到自己。
加入Canny边缘检测
canny算子用于边缘检测,可以绘制出物体的边缘轮廓特征,将其用于摄像机能够实时渲染出目标物体轮廓属性,以动态的人物为测试对象:
实现代码如下所示:
void CannyTest()
{
VideoCapture cap(0);
if (!cap.isOpened())
return ;
Mat edges;
namedWindow("edges", 1);
while(1)
{
Mat frame;
cap >> frame;
cvtColor(frame, edges, CV_BGR2GRAY);
GaussianBlur(edges, edges, Size(7, 7), 1.5, 1.5);
Canny(edges, edges, 0, 30, 3);
imshow("edges", edges);
if (waitKey(30) >= 0) break;
}
}
加入Sobel边缘检测
Sobel边缘检测算法比较简单,实际应用中效率比canny边缘检测效率要高,但是边缘不如Canny检测的准确,然而在很多实际应用的场合,sobel边缘却是首选,实现结果如下:
实现代码:
void SobelTest()
{
VideoCapture cap(0);
if (!cap.isOpened())
return;
Mat edges;
namedWindow("edges", 1);
while (1)
{
Mat frame;
cap >> frame;
Mat resultX, resultY, resultXY;
cvtColor(frame, edges, CV_BGR2GRAY);
//-------------Sobel边缘检测--------------
//X方向一阶边缘
Sobel(edges, resultX, CV_16S, 2, 0, 1);
convertScaleAbs(resultX, resultX);
//Y方向一阶边缘
Sobel(edges, resultY, CV_16S, 0, 1, 3);
convertScaleAbs(resultY, resultY);
//整幅图像的一阶边缘
resultXY = resultX + resultY;
imshow("edges", resultXY);
if (waitKey(30) >= 0) break;
}
}