OpenCV-制作视频红蓝3D效果
这个代码生成的视频,透过红色镜片会看到蓝色部分发黑,导致观感不好。
import cv2
import numpy as np
# 输入和输出视频文件路径
input_video_path = 'input_video.mp4'
output_video_path = 'output_video.mp4'
# 打开输入视频
cap = cv2.VideoCapture(input_video_path)
# 获取视频属性
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = int(cap.get(cv2.CAP_PROP_FPS))
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# 设置输出视频编码和属性(MJPG 编解码器)
fourcc = cv2.VideoWriter_fourcc(*'MJPG') # 更改为 MJPEG 编解码器
frame_width_out = frame_width - 10 # 考虑偏移量后的宽度
out = cv2.VideoWriter(output_video_path, fourcc, fps, (frame_width_out, frame_height))
# 定义视差偏移量(可根据需求调整)
offset = 10 # 偏移量,单位为像素
# 逐帧处理视频
frame_index = 0
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break # 结束读取
# 创建左右视图
left_view = frame[:, :-offset, :] # 左眼图像(去掉右边的一部分)
right_view = frame[:, offset:, :] # 右眼图像(去掉左边的一部分)
# 对左右视图进行颜色通道处理
left_red = left_view[:, :, 2] # 左图红色通道
right_green_blue = right_view[:, :, :2] # 右图绿色和蓝色通道
# 创建红蓝3D帧
height, width, _ = frame.shape
anaglyph_frame = np.zeros((height, width - offset, 3), dtype=np.uint8)
anaglyph_frame[:, :, 2] = left_red # 左眼的红色通道
anaglyph_frame[:, :, :2] = right_green_blue # 右眼的绿色和蓝色通道
# 保存到输出视频
out.write(anaglyph_frame)
frame_index += 1
print(f'Processing frame {frame_index}/{frame_count}', end='\r')
# 释放资源
cap.release()
out.release()
cv2.destroyAllWindows()
print("红蓝3D视频生成完成,输出路径为:", output_video_path)
这个代码生成的视频将上述代码红色镜片看蓝色部分发黑问题解决了,但是整体色调偏红,透过蓝色镜片看视频模糊且有发黑的情况,但立体感挺好。
import cv2
import numpy as np
# 输入和输出视频路径
input_video_path = 'input_video.mp4'
output_video_path = 'output_video.mp4'
# 打开输入视频
cap = cv2.VideoCapture(input_video_path)
# 获取视频属性
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = int(cap.get(cv2.CAP_PROP_FPS))
frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
# 设置输出视频(使用 mp4v 编码器)
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # 兼容 MP4 的编码器
out = cv2.VideoWriter(output_video_path, fourcc, fps, (frame_width - 10, frame_height))
# 定义视差偏移
offset = 10
# 逐帧处理视频
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# 左右视图
left_view = frame[:, :-offset, :]
right_view = frame[:, offset:, :]
# 红色通道(左眼)
left_red = cv2.normalize(left_view[:, :, 2], None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX)
# 蓝绿色通道(右眼)
right_green_blue = right_view[:, :, :2] // 2 # 降低亮度
# 创建红蓝3D帧
anaglyph_frame = np.zeros((frame_height, frame_width - offset, 3), dtype=np.uint8)
anaglyph_frame[:, :, 2] = left_red
anaglyph_frame[:, :, :2] = right_green_blue
# 保存帧
out.write(anaglyph_frame)
# 释放资源
cap.release()
out.release()
cv2.destroyAllWindows()
print("红蓝3D视频生成完成,输出路径为:", output_video_path)