• 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可以正常播放;

  • 相关阅读:
    Chrome 浏览器关闭后再打开,需要重新登录账号,解决办法
    金仓数据库 KingbaseES 插件参考手册(25. dict_xsyn)
    IS ATTENTION BETTER THAN MATRIX DECOMPOSITION
    bm19bm7
    Kubernetes集群故障排查—使用 crictl 对 Kubernetes 节点进行调试
    pod详解
    IP风险查询:抵御DDoS攻击和CC攻击的关键一步
    “2024上海智博会”为我国智能科技产业发展注入新的动力
    XTU-OJ 1412-Rotate Again
    K8S原来如此简单(三)Pod+Deployment
  • 原文地址:https://blog.csdn.net/weixin_43863869/article/details/127952369