opencv 启动摄像头 C++

时间:2021-12-07 06:30:15

http://blog.csdn.net/thefutureisour/article/details/7530177

在网上看了许多关于OpenCV启动摄像头的资料,但是,都是基于C语言的,代码又臭又长,(其实主要是因为我学的OpenCV就是用C++的,C语言的基本数据结构不太熟悉),所以一直想找一个用C++写的程序,最后让我在OpenCV自带的英文参考手册上找见了,整个代码30行都不到!nice啊!我对代码做了一点修改,发上来吧!

  1. #include <opencv2/highgui/highgui.hpp>
  2. #include <opencv2/imgproc/imgproc.hpp>
  3. #include <opencv2/core/core.hpp>
  4. using namespace cv;
  5. int main()
  6. {
  7. VideoCapture cap(0);
  8. if(!cap.isOpened())
  9. {
  10. return -1;
  11. }
  12. Mat frame;
  13. Mat edges;
  14. bool stop = false;
  15. while(!stop)
  16. {
  17. cap>>frame;
  18. cvtColor(frame, edges, CV_BGR2GRAY);
  19. GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
  20. Canny(edges, edges, 0, 30, 3);
  21. imshow("当前视频",edges);
  22. if(waitKey(30) >=0)
  23. stop = true;
  24. }
  25. return 0;
  26. }

对代码的几点说明:

1. VideoCapture类有两种用法,一种是VideoCapture(const string& filename)用来打开视频文件,一种是VideoCapture(int device)用来打开设备。

2. isOpened函数用来检测VideoCapture类是否打开成功。

3. C++版本的OpenCV有一个明显的好处,就是不需要释放操作(不论是视频还是图片),VideoCapture类的析构函数会自动帮你完成。

由于本人长相丑陋,所以对摄像头获取的彩色图像进行了一些简单的处理:转为灰度图像、高斯滤波,边沿检测。这样大家就不会受惊了,哈哈!