鱼眼视频的批量矫正算法
简介
鱼眼视频的批量矫正算法是一种用于视频流中的图像矫正技术,它能够通过自己设计校正系数,从而校正视频帧中的鱼眼失真,从而提高得到一个超广角的视频效果。
使用方法
矫正数据存储:将待矫正的视频存储在input_videos文件夹中。
设置矫正系数:在代码中,矫正系数k取0-1之间,值越小矫正越弱。(注:如果一次矫正达不到矫正效果,可将校正后的视频放入input_videos文件夹中二次矫正。)
输出矫正后视频:矫正后的视频存储在corrected_videos文件夹中。
import cv2
import os
import glob
import numpy as np
def load_videos_from_folder(folder_path):
"""批量加载文件夹中的所有视频"""
video_paths = glob.glob(os.path.join(folder_path, '*.mp4'))
return video_paths
def fisheye_correction(frame, k=0.3):
"""对视频帧进行鱼眼矫正。参数k控制矫正强度,值越低矫正越弱"""
h, w = frame.shape[:2]
fx = fy = w
cx, cy = w / 2, h / 2
# 鱼眼校正的相机矩阵和失真系数
K = np.array([[fx, 0, cx], [0, fy, cy], [0, 0, 1]])
D = np.array([-k, k, 0, 0])
# 计算矫正映射
map1, map2 = cv2.fisheye.initUndistortRectifyMap(K, D, np.eye(3), K, (w, h), cv2.CV_16SC2)
corrected_frame = cv2.remap(frame, map1, map2, interpolation=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT)
return corrected_frame
def process_videos(input_folder, output_folder, k=0.3):
"""加载视频,逐帧进行鱼眼矫正,并保存矫正后的视频"""
if not os.path.exists(output_folder):
os.makedirs(output_folder)
video_paths = load_videos_from_folder(input_folder)
for video_path in video_paths:
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"无法打开视频文件:{video_path}")
continue
# 获取视频属性
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = cap.get(cv2.CAP_PROP_FPS)
# 输出文件路径
output_path = os.path.join(output_folder, os.path.basename(video_path))
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))
print(f"正在处理视频:{video_path}")
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# 鱼眼矫正
corrected_frame = fisheye_correction(frame, k)
out.write(corrected_frame)
cap.release()
out.release()
print(f"已保存矫正后的视频:{output_path}")
if __name__ == "__main__":
# 输入和输出文件夹路径
input_folder = "./input_videos"
output_folder = "./corrected_videos"
# 矫正系数k,0-1之间,值越小矫正越弱
correction_coefficient = 0.02
# 批量处理视频
process_videos(input_folder, output_folder, correction_coefficient)
原文地址:https://blog.csdn.net/m0_53605808/article/details/143749192
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!