2.使用树梅派进行视频录制

条件: 树梅派安装opencv和免驱动的摄像头

c源码:

#include <iostream>
#include "opencv.hpp"

/**
 * 一个程序捕获USB摄像头和视频保存一个文件使用OpenCV。
 */
using namespace std;
using namespace cv;

int main(int argc, char **argv) {
  if (argc < 2) {
    cout << "Usage: ./video_capture output_video_file_name
" << endl;
    return 1;
  }

  string outputVideoFile = argv[1];        //输出的视频文件的路径

  VideoCapture videoCapture(0);          //初始化结构体,用于捕获摄像入视频 0为默认的摄像头
  if (!videoCapture.isOpened()){
    cout << "Failed to open the default camera" << endl;
    return 1;
  }

  /* 获取视频帧的宽度和高度 */
  double frameWidth = videoCapture.get(CV_CAP_PROP_FRAME_WIDTH);
  double frameHeight = videoCapture.get(CV_CAP_PROP_FRAME_HEIGHT);
  cout << "Frame size is [" << frameWidth << "x" << frameHeight << "]" << endl;
/* 创建一个VideoWriter的对象将视频流写入文件 */
  Size frameSize(static_cast<int>(frameWidth), static_cast<int>(frameHeight));
 /* videoWriter(输出的文件名,输出文件的编码,帧率,帧的尺寸,是否是彩色(尽支持win)) */
 //('D', 'I', 'V', 'X') mp4
  VideoWriter videoWriter(outputVideoFile.c_str(), CV_FOURCC('D', 'I', 'V', 'X'), 10, frameSize, true);
  if (!videoWriter.isOpened()) {
    cout << "Failed to initialize the VideoWriter" << endl;
    return 1;
  }

  while (true) {
    Mat frame;
    if (!videoCapture.read(frame)) {  // 抓住,解码并返回下一个视频帧
      cout << "Failed to read a video frame" << endl;
      break;
    }

    videoWriter.write(frame);  // 写入文件的框架
    if (27 == waitKey(30)) {   // 等待按下“ESC”键(注意:不是工作如果没有窗口被创建!)
      cout << "ESC key pressed, stop capturing video" << endl;
      break;
    }
  }

  return 0;
}

脚本

  capture-video-from-camera-using-opencv.sh

#!/bin/bash
# A script to invoke a C program to capture video from USB camera & save to a file using OpenCV.

CURRENT_DIR=`dirname "$0"`
WORKING_HOME=`cd "$CURRENT_DIR"; pwd`

SOURCE_FILE=$WORKING_HOME/video_capture.cpp
COMPILED_BIN=$WORKING_HOME/video_capture
OUTPUT_VIDEO_FILE=$WORKING_HOME/webcam.avi

rm -f $OUTPUT_VIDEO_FILE

# compile the source code if the executable bin not exists
if [ ! -f $COMPILED_BIN ]; then
    echo "Compiling $SOURCE_FILE ..."
    g++ -I/usr/include/opencv2/  `pkg-config --cflags opencv --libs opencv` $SOURCE_FILE -o $COMPILED_BIN
    if [ $? -ne 0 ]; then
    echo "Failed to compile $SOURCE_FILE"
    exit 1
    fi
fi

# run the program
echo "Start capturing video & save to file $OUTPUT_VIDEO_FILE ..."
$COMPILED_BIN $OUTPUT_VIDEO_FILE
原文地址:https://www.cnblogs.com/jikexianfeng/p/5705396.html