• Opencv(C++)笔记--打开摄像头、保存摄像头视频


    1--打开摄像头

    关键代码语句:

    ① VideoCapture cam(0);

    ② cam.read(img);

    ③ imshow("cam", img);

    1. # include
    2. # include
    3. using namespace cv;
    4. using namespace std;
    5. int main(int argc, char *argv[]){
    6. // 打开摄像头
    7. VideoCapture cam(0);
    8. if (!cam.isOpened()){
    9. cout << "cam open failed!" << endl;
    10. getchar();
    11. return -1;
    12. }
    13. cout << "cam open success!" << endl;
    14. namedWindow("cam");
    15. Mat img;
    16. for(;;){
    17. cam.read(img); // 读帧
    18. if (img.empty()) break;
    19. imshow("cam", img); // 显示每一帧
    20. if (waitKey(5) == 'q') break; // 键入q停止
    21. }
    22. return 0;
    23. }

    2--保存摄像头视频

    关键代码:

    ①VideoWriter vw

    ②vw.open():fourcc指定编码格式(常见编码方式)、fps指定帧率、Size指定大小

    ③vw.write()

    1. # include
    2. # include
    3. using namespace cv;
    4. using namespace std;
    5. int main(int argc, char *argv[]){
    6. // 打开摄像头
    7. VideoCapture cam(0);
    8. if (!cam.isOpened()){
    9. cout << "cam open failed!" << endl;
    10. getchar();
    11. return -1;
    12. }
    13. cout << "cam open success!" << endl;
    14. namedWindow("cam");
    15. Mat img;
    16. VideoWriter vw;
    17. int fps = cam.get(CAP_PROP_FPS); // 获取原视频的帧率
    18. if (fps <= 0) fps = 25;
    19. vw.open("./out1120.avi",
    20. VideoWriter::fourcc('X', '2', '6', '4'),
    21. fps,
    22. Size(cam.get(CAP_PROP_FRAME_WIDTH),
    23. cam.get(CAP_PROP_FRAME_HEIGHT))
    24. );
    25. if (!vw.isOpened()){ // 判断VideoWriter是否正常打开
    26. cout << "videoWriter open failed!" << endl;
    27. getchar();
    28. return -1;
    29. }
    30. cout << "videoWriter open sucess!" << endl;
    31. for(;;){
    32. cam.read(img); // 读帧
    33. if (img.empty()) break;
    34. imshow("cam", img); // 展示当前帧
    35. /*
    36. 这里可以添加对当前帧的处理操作
    37. */
    38. vw.write(img); // 保存当前帧
    39. if (waitKey(5) == 'q') break; // 键入q停止
    40. }
    41. return 0;
    42. }

    注:在Windows上执行上述代码可能会报以下错误:

    解决方法:在输出的网址下载对应版本的库文件,放在执行文件.exe的同级目录即可,或者将该dll文件的路径添加到系统变量path中。

     结果:生成的out1120.avi可以正常播放;

  • 相关阅读:
    终极Hadoop大数据教程
    我也来扒一扒python的内存回收机制!
    CSS进阶
    synchronized修饰类的注意事项
    打造全身视角的医院可视化能源监测管理平台,实现医院能源可视化管理
    VMware ubuntu 新虚拟机的创建
    【CV】第 4 章:介绍卷积神经网络
    MySQL表的增删查改(嘎嘎详细~
    【软考中级信安】第三章--密码学基本理论
    ETL调度同步工具比较-Kettle、DolphinSchedule、DataX
  • 原文地址:https://blog.csdn.net/weixin_43863869/article/details/127952369