上篇文章中基于OpenCV实现图像处理后,类似的,也可以对视频进行处理。OpenCV库可以将视频的每一帧读取出来,然后对每一帧图像做相应的操作,并保存成新的视频。
- 读取视频,获取相关参数
python
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))
- 设置图像处理参数
python
# 设置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相同大小的矩阵
- 设置保存的视频的信息
python
# 设置视频格式
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)
- 逐帧处理视频图像并保存
python
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