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)

青灯夜游
Release: 2018-10-19 16:11:32
forward
6597 people have browsed it

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()
Copy after login

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()
Copy after login

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()
Copy after login

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!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template