Home >Backend Development >Python Tutorial >How to implement video reading and saving functions in python (code example)

How to implement video reading and saving functions in python (code example)

青灯夜游
青灯夜游forward
2018-10-19 16:10:436607browse

This article brings you an introduction to how python implements video reading and saving functions. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1.Open the camera

#打开摄像头
import cv2
cap = cv2.VideoCapture(0)
while(True):
    ret,frame = cap.read()#返回两个值,第一个为bool类型,如果读到帧返回True,如果没读到帧返回False,第二个值为帧图像
    gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    cv2.imshow('frame',gray)
    if cv2.waitKey(1)==27:
        break
cap.release()
cv2.destroyAllWindows()

2.Read the video file

#打开视频文件
import cv2
cap = cv2.VideoCapture('vtest.avi')
while(True):
    ret,frame = cap.read()#返回两个值,第一个为bool类型,如果读到帧返回True,如果没读到帧返回False,第二个值为帧图像 
    if(ret):
        gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        cv2.imshow('input',gray)
    else:
        break
    if cv2.waitKey(1)==27:
        break
cap.release()
cv2.destroyAllWindows()

3.Save the video file

#保存视频文件
import cv2
fourcc = cv2.VideoWriter_fourcc(*'XVID')#视频编码格式
out = cv2.VideoWriter('save.avi',fourcc,20,(640,480))#第三个参数为帧率,第四个参数为每帧大小
cap = cv2.VideoCapture(0)
while(True):
    ret,frame = cap.read()
    if(ret):
        cv2.imshow('input',frame)
        out.write(frame)
    else:
        break
    if(cv2.waitKey(1)==27):
        break
cap.release()
out.release()
cv2.destroyAllWindows()

The above is the detailed content of How to implement video reading and saving functions in python (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete