Python OpenCV 视频抽帧处理并保存

上篇文章中基于OpenCV实现图像处理后,类似的,也可以对视频进行处理。OpenCV库可以将视频的每一帧读取出来,然后对每一帧图像做相应的操作,并保存成新的视频。

1.  读取视频,获取相关参数

import cv2
import numpy as np

capture = cv2.VideoCapture(video_name)
width = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = int(capture.get(cv2.CAP_PROP_FPS))
frame_count = int(capture.get(cv2.CAP_PROP_FRAME_COUNT))

2. 设置图像处理参数


# 设置R/G/B因子
red = 149
green = 126
blue = 91

red_factor = np.full((height, width), red-127, dtype="uint8")  # 创建与image相同大小的矩阵
green_factor = np.full((height, width), green-127, dtype="uint8")  # 创建与image相同大小的矩阵
blue_factor = np.full((height, width), blue-127, dtype="uint8")  # 创建与image相同大小的矩阵

3. 设置保存的视频的信息

# 设置视频格式
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
# 调用VideoWrite()函数
size = (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
video_writer = cv2.VideoWriter(video_name_output, fourcc, fps, size)

4. 逐帧处理视频图像并保存


        while True:
            ret, image = capture.read() 
            if not ret:
                break  

            B, G, R = cv2.split(image)  # 分离出图片的B,R,G颜色通道
            R_temp = R + red_factor
            G_temp = G + green_factor
            B_temp = B + blue_factor
            output = cv2.merge([B_temp, G_temp, R_temp])

            if not video_writer is False:
                video_writer.write(output)

            k = cv2.waitKey(20)
            # q键退出
            if k & 0xff == ord('q'):
                break

你可能感兴趣的:(python,python,opencv,视频)