OpenCV-Python视频的读取及保存

Capture Video from Camera

从摄像头中获取视频:

要捕捉视频,需要创建一个VideoCapture对象。它的参数可以是设备索引或视频文件的名称(下面会讲到)。设备索引只是指定哪台摄像机的号码。0代表第一台摄像机、1代表第二台摄像机。之后,可以逐帧捕捉视频。但最后,不要忘记释放捕获。

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

while(True):
    # Capture frame-by-frame
    ret, frame = cap.read()

    # Our operations on the frame come here
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Display the resulting frame
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

cap.read():返回一个布尔值(True / False)。如果帧被正确读取,则返回true,否则返回false。可以通过检查这个返回值来判断视频是否结束。

cap.isOpened():检查cap是否被初始化。若没有初始化,则使用cap.open()打开它。当cap没有初始化时,上面的代码会报错。

cap.get(propId):访问视频的某些功能,其中propId是一个从0到18的数字,每个数字表示视频的属性(Property Identifier)。其中一些值可以使用cap.set(propId,value)进行修改,value是修改后的值。

举个例子:我通过cap.get(3)和cap.get(4)来检查帧的宽度和高度,默认的值是640x480。但我想修改为320x240,可以使用ret = cap.set(3, 320)和ret = cap.set(4, 240)。


Playing Video from file

从文件中播放视频:

和从相机捕获视频相同,只需更改相机索引与视频文件名。 在显示帧时,选择适当的cv2.waitKey()时间,如果该值太小,视频会非常快,如果它太大,视频会很慢(这可以用来慢动作显示视频)。 正常情况下,25毫秒即可。

import numpy as np
import cv2

cap = cv2.VideoCapture('vtest.avi')

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

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

Saving a Video

保存视频:

创建一个VideoWriter对象,指定输出文件名(例如:output.avi)。之后指定FourCC代码(FourCC是用于指定视频编解码器的4字节代码。可用代码列表)。接下来传递每秒帧数(fps)和帧大小。最后一个是isColor标志,如果它为True,编码器编码成彩色帧,否则编码成灰度框帧。

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,0)

        # write the flipped frame
        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

官方文档

猜你喜欢

转载自blog.csdn.net/qq_25436597/article/details/79621833