Opencv-Python视频处理

一、视频的读取

OpenCV为视频的读入提供了一个类VideoCapture,用于获取相机设备并捕获图像和视频,或是从文件中捕获。

  • 从相机设备读取:cv2.VideoCapture(Index)——Index默认为0,可以根据相机数目增加,cap.read()返回布尔值,最后记得释放捕获
import numpy as np
import cv2

cap = cv2.VideoCapture(0)
ret = cap.set(3,320)####设置捕获窗口大小
ret = cap.set(4,240)

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

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)####彩色图像用BGR2RGB

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

cap.release()
cv2.destroyAllWindows()
  • 从视频文件捕捉:VideoCapture(filename):
import numpy as np
import cv2

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

while(cap.isOpened()):
    ret, frame = cap.read()##ret返回布尔量

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

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

cap.release()
cv2.destroyAllWindows()

二、视频保存

主要使用函数:cv2.VideoWriter(filename,  fourcc, fps,  frameSize)

参数详解

  • filename:指定的文件名
  • fourcc:编码格式,如CV_FOURCC(‘P’,’I’,’M’,’1’)是MPEG-1格式,CV_FOURCC(‘M’,’G’,’P’,’G’)为motion-jpeg格式
  • fps:帧率
  • frameSize:视频的尺寸大小,(320,240)、(640,480)
#!/usr/bin/env python
 
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
i = 0
while( i < 18):
    i = i+1
    print(cap.get(i))
 
ret = cap.set(3,320)
ret = cap.set(4,240)
 
#output info
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (320,240))
while(cap.isOpened()):
    ret, frame = cap.read()
    if ret == True:
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    
        out.write(frame)
 
        cv2.imshow('image', gray)
        k = cv2.waitKey(1)
        if (k & 0xff == ord('q')):
            break
    else:
        break
 
cap.release()
out.release()
cv2.destroyAllWindows()

 

你可能感兴趣的:(Opencv)