OpenCv(图像入门篇)-读取,显示,保存视频

从相机中读取视频

import numpy as np
import cv2 as cv
#选择摄像头
cap = cv.VideoCapture(0)
#如果摄像头没打开,后面程序不执行,重新调
if not cap.isOpened():
    print("Cannot open camera")
    exit()
#死循环
while True:
    #ret返回是否正确读取了帧,frame为帧传递对象
    ret,frame = cap.read()
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    #选取风格
    gray = cv.cvtColor(frame,cv.COLOR_BGR2RGBA)
    #显示结果
    cv.imshow('frame',gray)
    if cv.waitKey(1) == ord('q'):
        break
#工作完成,释放资源
cap.release()
cv.destroyAllWindows()  

从文件读取视频

import numpy as np
import cv2 as cv
#将摄像头索引换成视频名称即可
cap = cv.VideoCapture('output.avi')
#如果摄像头没打开,后面程序不执行,重新调
if not cap.isOpened():
    print("Cannot open camera")
    exit()
#死循环
while True:
    #ret返回是否正确读取了帧,frame为帧传递对象
    ret,frame = cap.read()
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    #选取风格
    gray = cv.cvtColor(frame,cv.COLOR_BGR2RGBA)
    #显示结果
    cv.imshow('frame',gray)
    if cv.waitKey(1) == ord('q'):
        break
#工作完成,释放资源
cap.release()
cv.destroyAllWindows() 

保存视频

import numpy as np
import cv2 as cv
#选择摄像头
cap = cv.VideoCapture(0)
#建立输出视频对象,并选择视频格式
fourcc = cv.VideoWriter_fourcc(*'XVID')
#输出
out = cv.VideoWriter('output.avi',fourcc, 20.0,(640,480))
#如果摄像头没打开,后面程序不执行,重新调
if not cap.isOpened():
    print("Cannot open camera")
    exit()
#死循环
while True:
    #ret返回是否正确读取了帧,frame为帧传递对象
    ret,frame = cap.read()
    if not ret:
        print("Can't receive frame (stream end?). Exiting ...")
        break
    #视频角度变换
    frame = cv.flip(frame,0)
    #输出
    out.write(frame)
    #显示结果
    cv.imshow('frame',frame)
    if cv.waitKey(1) == ord('q'):
        break
#工作完成,释放资源
cap.release()
out.release()
cv.destroyAllWindows()  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值