opencv视频的读取与存储

视觉处理中的基础操作

  • 1,处理视频的每一帧,并保存成图像存入指定路径
    • 方法一:cv2.imencode
    • 方法二:cv2.imwrite
  • 2,OpenCV读取视频,逐帧处理后,保存成视频:cv2.VideoWrite.write(frame)
    • 版本一,cpp代码
    • 方法二,python版本

1,处理视频的每一帧,并保存成图像存入指定路径

方法一:cv2.imencode

cv2.imencode('.jpg', image)[1].tofile(frames_save_path + "/frame%d.jpg" % count)

例程如下:

import cv2


def video2frame(videos_path, frames_save_path, time_interval):
    '''
    :param videos_path: 视频的存放路径
    :param frames_save_path: 视频切分成帧之后图片的保存路径
    :param time_interval: 保存间隔
    :return:
    '''
    vidcap = cv2.VideoCapture(videos_path)
    success, image = vidcap.read()
    count = 0
    while success:
        success, image = vidcap.read()
        count += 1
        if count % time_interval == 0:
            cv2.imencode('.jpg', image)[1].tofile(frames_save_path + "/frame%d.jpg" % count)
        # if count == 20:
        #   break
    print(count)


if __name__ == '__main__':
    videos_path = r'C:\Users\16078\Desktop\5.avi'
    frames_save_path = r'.\split'
    time_interval = 1  # 隔一帧保存一次
    video2frame(videos_path, frames_save_path, time_interval)

方法二:cv2.imwrite

创建文件夹

foldername = 'my_test/weights/len{}_bs{}_per{}_epo{}'.format(len(res_x), batch_size, train_num, epoch)
word_name = os.path.exists(foldername)
# 判断文件是否存在:不存在创建
if not word_name:
   os.makedirs(foldername)
#保存图片
TrackingFrame_Pathout = ("./output/frame_" + str(num) + ".jpg")
cv2.imwrite(TrackingFrame_Pathout,img)

2,OpenCV读取视频,逐帧处理后,保存成视频:cv2.VideoWrite.write(frame)

版本一,cpp代码

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
 
using namespace std;
using namespace cv;

int main(){
	//读取视频
	cv::VideoCapture capture("/home/nx/Pictures/input.mp4");  
	long totalFrameNumber = capture.get(CAP_PROP_FRAME_COUNT);
	cout<<"整个视频共"<<totalFrameNumber<<"帧"<<endl;
	capture.set( CAP_PROP_POS_FRAMES,0);
	
	//获取帧率
	double rate = capture.get(CAP_PROP_FPS);
	cout<<"帧率为:"<<rate<<endl;
	
	int delay = 1000/rate;
	cv::Mat frame;
	if(!capture.read(frame))
	    {
	    	cout<<"读取视频失败"<<endl;
	        return -1;
	    }
	cout<<"图片宽width为:"<<frame.rows<<endl;
	cout<<"图片高height为:"<<frame.cols<<endl;
	int isColor = 1;
	int fps = rate;
	int frameWidth = frame.rows;
	int frameHeight = frame.cols;
	cv::VideoWriter writer("output.avi", VideoWriter::fourcc('M','J','P','G'), fps, Size(frameWidth, frameHeight), isColor);
	for (;;)
	{
		frame = frame.clone();  //对图片进行处理
		writer.write(frame);
		imshow("frame",frame);
		waitKey(delay);//因为图像处理需要消耗一定时间,所以图片展示速度比保存视频要慢
	    //读取下一帧
	    if(!capture.read(frame))
	    {
	            cout<<"读取视频失败"<<endl;
	            return -1;
	    }
	}
	capture.release();
	waitKey(0);
	return 0;
}

方法二,python版本

	  cap = cv2.VideoCapture(video_path)
    SAVE_VIDEO = True
    if SAVE_VIDEO:
        fourcc = cv2.VideoWriter_fourcc(*'XVID')
        out = cv2.VideoWriter('kalman_output.avi', fourcc, 20,(768,576))
    while (True):
        ret, frame = cap.read()
        if SAVE_VIDEO:
            out.write(frame)    

你可能感兴趣的:(OpenCV,opencv,计算机视觉,图像处理)