简介
鱼眼视频的批量矫正算法是一种用于视频流中的图像矫正技术,它能够通过自己设计校正系数,从而校正视频帧中的鱼眼失真,从而提高得到一个超广角的视频效果。
使用方法
矫正数据存储:将待矫正的视频存储在input_videos文件夹中。
设置矫正系数:在代码中,矫正系数k取0-1之间,值越小矫正越弱。(注:如果一次矫正达不到矫正效果,可将校正后的视频放入input_videos文件夹中二次矫正。)
输出矫正后视频:矫正后的视频存储在corrected_videos文件夹中。
import cv2
import os
import glob
import numpy as npdef load_videos_from_folder(folder_path):"""批量加载文件夹中的所有视频"""video_paths = glob.glob(os.path.join(folder_path, '*.mp4'))return video_pathsdef fisheye_correction(frame, k=0.3):"""对视频帧进行鱼眼矫正。参数k控制矫正强度,值越低矫正越弱"""h, w = frame.shape[:2]fx = fy = wcx, 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_framedef 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)