栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

OpenCV笔记012————Video Read and Write

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

OpenCV笔记012————Video Read and Write

视频文件的读写

Video Read and Write的代码注释:

import cv2 as cv
import numpy as np


capture = cv.VideoCapture("dataset/train/test_cp.avi")
# capture = cv.VideoCapture(0) 打开摄像头
# 此处我是先打开摄像头录制一段视频
# 视频保存在所在环境文件夹里,录制时按esc结束录制
# 完成后读取所录制的视频

height = capture.get(cv.CAP_PROP_frame_HEIGHT)
width = capture.get(cv.CAP_PROP_frame_WIDTH)
count = capture.get(cv.CAP_PROP_frame_COUNT)
fps = capture.get(cv.CAP_PROP_FPS)
print(height, width, count, fps)
out = cv.VideoWriter("dataset/train/test_cp.avi", cv.VideoWriter_fourcc('D', 'I', 'V', 'X'), 15,
                     (np.int(width), np.int(height)), True)
while True:
    ret, frame = capture.read()
    if ret is True:
        cv.imshow("video-input", frame)
        out.write(frame)
        c = cv.waitKey(50)
        if c == 27: # ESC
            break
    else:
        break

capture.release()
out.release()

结果如图:

总结

读取出视频,并将视频保存
cv.VideoCapture(path):path填写视频的路径
cv.VideoCapture(0):path填写为0的话,默认调用摄像头
注:不支持音频编码与解码保存,不是一个音视频处理的库!保存文件最大支持单个文件为2G
详细参考此代码,源自博客:

#include 
#include

using namespace std;
using namespace cv;

int main() {
	//存放读取的每一帧和被转化后的每一帧
	Mat in_f, out_f;

	//打开自带摄像头
	VideoCapture readCapture(0);
	//判断摄像头是否打开成功
	if (!readCapture.isOpened()) {
		cout << "摄像头打开错误!" << endl;
		return -1;
	}

	//获取读入视频文件的高度和宽度
	int width=(int)readCapture.get(CAP_PROP_frame_WIDTH);
	int height=(int)readCapture.get(CAP_PROP_frame_HEIGHT);

	//定义存放读取视频的地址
	char myVideo[] = "D:/test/myVideo3.avi";
	//定义每一秒读取的帧数
	double fps = 30;

	//按照规定的帧数写入读取的视频文件


	//当存入视频为灰度色彩时,isColor必须设置为0
	//否则,不需要写最后一个参数,否则会出现问题。
	VideoWriter writerCapture(myVideo,VideoWriter::fourcc('X', 'V', 'I', 'D'),fps,Size(width,height),0);
	if (!writerCapture.isOpened()) {
		cout << "写入视频错误" << endl;
		return -1;
	}
	
	//显示摄像头读取的视频和转换成灰度空间的视频文件
	while (true)
	{
		//从摄像机读取帧(抓取并解码)
		readCapture >> in_f;
		//将帧转换为灰度
		cvtColor(in_f, out_f, COLOR_BGR2GRAY);
		//将幀写入视频文件(编码并保存)
		writerCapture << out_f;
		imshow("read", in_f);
		imshow("write", out_f);
		if (waitKey(1000 / fps) >= 0) {
			break;
		}
	}
	readCapture.release();
	return 0;
}

有关视频还有同上代码博主的视频基础

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/304148.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号