learn opencv-使用OpenCV(C ++ / Python)读取,写入和显示视频

参考:
https://github.com/spmallick/learnopencv


使用OpenCV(C ++ / Python)读取,写入和显示视频

在这篇文章中,我们将学习如何在OpenCV中读取,写入和显示视频。

那么,首先,什么是视频? 视频是一系列快速移动的图像。 接下来显而易见的问题是图片移动速度有多快? 图像转换速度的度量由一个称为每秒帧数(FPS)的度量给出。 当有人说视频的FPS是40时,意味着每秒钟显示40个图像。 或者,每25毫秒后,显示一个新的框架。

其他重要的属性是框架的宽度和高度。

Reading a Video

在OpenCV中,视频可以通过使用连接到计算机的摄像头或通过读取视频文件来读取。 读视频文件的第一步是创建一个VideoCapture对象。 它的参数可以是设备索引,也可以是要读取的视频文件的名称。

在大多数情况下,只有一台摄像机连接到系统。 所以,我们所做的只是传递’0’,OpenCV使用连接到计算机的唯一相机。 当多台摄像机连接到电脑时,我们可以通过’1’来选择第二台摄像机,通过’2’来选择第三台摄像机,等等。

Python

# Create a VideoCapture object and read from input file
# If the input is taken from the camera, pass 0 instead of the video file name.

cap = cv2.VideoCapture('chaplin.mp4')

C++

// Create a VideoCapture object and open the input file
// If the input is taken from the camera, pass 0 instead of the video file name

VideoCapture cap("chaplin.mp4"); 

在创建VideoCapture对象之后,我们可以逐帧捕捉视频。

Displaying a video

读取视频文件后,我们可以逐帧显示视频。视频的一个框架就是一个图像,我们用与显示图像相同的方式显示每一个框架,即我们使用函数imshow()。

和图像一样,我们在imshow()函数之后使用waitKey()来暂停视频中的每一帧。在图像的情况下,我们将’0’传递给waitKey()函数,但是为了播放视频,我们需要将大于’0’的数字传递给waitKey()函数。这是因为’0’会使视频中的帧暂停无限的时间,并且在视频中我们需要每个帧仅在有限的时间间隔内显示,所以我们需要传递大于’0’的数字,到waitKey()函数。这个数字等于我们希望显示每个帧的时间(以毫秒为单位)。

在从网络摄像头读取帧时,使用waitKey(1)是合适的,因为即使我们在waitKey中指定了1 ms的延迟,显示帧速率也会受到网络摄像头帧速率的限制。

在从正在处理的视频中读取帧时,将时间延迟设置为1 ms可能仍然合适,以便线程被释放以执行我们想要执行的处理。

在极少数情况下,当播放需要达到一定的帧率时,我们可能希望延迟高于1毫秒。

阅读和显示视频文件的Python和C ++实现如下。

Python

import cv2
import numpy as np

# Create a VideoCapture object and read from input file
# If the input is the camera, pass 0 instead of the video file name
cap = cv2.VideoCapture('chaplin.mp4')

# Check if camera opened successfully
if (cap.isOpened()== False): 
  print("Error opening video stream or file")

# Read until video is completed
while(cap.isOpened()):
  # Capture frame-by-frame
  ret, frame = cap.read()
  if ret == True:

    # Display the resulting frame
    cv2.imshow('Frame',frame)

    # Press Q on keyboard to  exit
    if cv2.waitKey(25) & 0xFF == ord('q'):
      break

  # Break the loop
  else: 
    break

# When everything done, release the video capture object
cap.release()

# Closes all the frames
cv2.destroyAllWindows()

C++

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

using namespace std;
using namespace cv;

int main(){

  // Create a VideoCapture object and open the input file
  // If the input is the web camera, pass 0 instead of the video file name
  VideoCapture cap("chaplin.mp4"); 

  // Check if camera opened successfully
  if(!cap.isOpened()){
    cout << "Error opening video stream or file" << endl;
    return -1;
  }

  while(1){

    Mat frame;
    // Capture frame-by-frame
    cap >> frame;

    // If the frame is empty, break immediately
    if (frame.empty())
      break;

    // Display the resulting frame
    imshow( "Frame", frame );

    // Press  ESC on keyboard to exit
    char c=(char)waitKey(25);
    if(c==27)
      break;
  }

  // When everything done, release the video capture object
  cap.release();

  // Closes all the frames
  destroyAllWindows();

  return 0;
}

Writing a video

在完成逐帧捕捉和处理视频之后,我们要做的下一步就是保存视频。

对于图像来说,它很简单。 我们只需要使用cv2.imwrite()。 但对于视频,我们需要更努力一点。 我们需要创建一个VideoWriter对象。 首先,我们应该指定输出文件的格式(例如:output.avi)。 然后,我们应该指定FourCC码和每秒帧数(FPS)。 最后,应该传递帧的大小。

Python

# Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file.
# Define the fps to be equal to 10. Also frame size is passed.

out = cv2.VideoWriter('outpy.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height))

C++

// Define the codec and create VideoWriter object.The output is stored in 'outcpp.avi' file.
// Define the fps to be equal to 10. Also frame size is passed.

  VideoWriter video("outcpp.avi",CV_FOURCC('M','J','P','G'),10, Size(frame_width,frame_height));

FourCC是用于指定视频编解码器的4字节代码。 可用代码列表可在fourcc.org上找到。 有许多FOURCC代码可用,但是在这篇文章中,我们将只保存成MJPG。

注意:根据系统上编解码器的可用性,以上列出的FourCC代码中只有少数可用于您的系统。 有时,即使特定的编解码器可用,OpenCV也可能无法使用它。 MJPG是一个安全的选择。

下面是从摄像头捕捉实时流并将其写入文件的Python和C ++实现。

Python

import cv2
import numpy as np

# Create a VideoCapture object
cap = cv2.VideoCapture(0)

# Check if camera opened successfully
if (cap.isOpened() == False): 
  print("Unable to read camera feed")

# Default resolutions of the frame are obtained.The default resolutions are system dependent.
# We convert the resolutions from float to integer.
# 默认分辨率取决于系统。
# 我们将分辨率从float转换为整数。
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))

# Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file.
# 定义编解码器并创建VideoWriter对象。输出存储在“outpy.avi”文件中。
out = cv2.VideoWriter('outpy.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height))

while(True):
  ret, frame = cap.read()

  if ret == True: 

    # Write the frame into the file 'output.avi'
    out.write(frame)

    # Display the resulting frame    
    cv2.imshow('frame',frame)

    # Press Q on keyboard to stop recording
    if cv2.waitKey(1) & 0xFF == ord('q'):
      break

  # Break the loop
  else:
    break 

# When everything done, release the video capture and video write objects
cap.release()
out.release()

# Closes all the frames
cv2.destroyAllWindows() 

C++

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

using namespace std;
using namespace cv;

int main(){

  // Create a VideoCapture object and use camera to capture the video
  VideoCapture cap(0); 

  // Check if camera opened successfully
  if(!cap.isOpened())
  {
    cout << "Error opening video stream" << endl; 
    return -1; 
  } 

  // Default resolution of the frame is obtained.The default resolution is system dependent. 
  int frame_width = cap.get(CV_CAP_PROP_FRAME_WIDTH); 
  int frame_height = cap.get(CV_CAP_PROP_FRAME_HEIGHT); 

  // Define the codec and create VideoWriter object.The output is stored in 'outcpp.avi' file. 
  VideoWriter video("outcpp.avi",CV_FOURCC('M','J','P','G'),10, Size(frame_width,frame_height)); 
  while(1)
  { 
    Mat frame; 

    // Capture frame-by-frame 
    cap >> frame;

    // If the frame is empty, break immediately
    if (frame.empty())
      break;

    // Write the frame into the file 'outcpp.avi'
    video.write(frame);

    // Display the resulting frame    
    imshow( "Frame", frame );

    // Press  ESC on keyboard to  exit
    char c = (char)waitKey(1);
    if( c == 27 ) 
      break;
  }

  // When everything done, release the video capture and write object
  cap.release();
  video.release();

  // Closes all the windows
  destroyAllWindows();
  return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值