import cv2
from moviepy.editor import VideoFileClip
import numpy as np
import os
# 视频文件路径
video_path = 'test1.mp4'
# 初始化视频读取器
cap = cv2.VideoCapture(video_path)
# 检查视频是否成功打开
if not cap.isOpened():
print("Error: Could not open video.")
exit()
# 初始化变量
frame_rate = cap.get(cv2.CAP_PROP_FPS) # 获取帧率
blank_duration_threshold = frame_rate * 10 # 空白持续时间阈值,单位为帧(假设10秒)
start_time = 0 # 当前章节的开始时间
blank_start_time = None # 空白部分的开始时间
chapters = [] # 存储章节的列表
# 读取视频帧
frame_count = 0
while True:
ret, frame = cap.read()
if not ret:
break # 如果没有帧了,退出循环
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # 转换为灰度图
_, frame_without_blank = cv2.threshold(gray, 1, 255, cv2.THRESH_BINARY) # 二值化处理
if np.sum(frame_without_blank) == 0: # 检测空白帧
if blank_start_time is None:
blank_start_time = frame_count
else:
if blank_start_time is not None:
# 检测到非空白帧,检查空白帧持续时间是否超过阈值
if (frame_count - blank_start_time) >= blank_duration_threshold:
end_time = (frame_count - 1) / frame_rate
chapters.append((start_time, end_time))
start_time = frame_count / frame_rate # 设置新章节的开始时间
blank_start_time = None
# 更新帧计数
frame_count += 1
# 处理视频末尾的章节
if chapters and chapters[-1][1] < frame_count / frame_rate:
chapters[-1] = (chapters[-1][0], frame_count / frame_rate)
# 释放视频读取器
cap.release()
# 使用moviepy分割视频
if chapters:
video = VideoFileClip(video_path)
for i, (start, end) in enumerate(chapters):
chapter_clip = video.subclip(start, end)
chapter_clip.write_videofile(f"chapter_{i+1}.mp4", codec="libx264")
print(f"Chapter {i+1} saved as chapter_{i+1}.mp4")
video.close()
else:
print("No chapters found.")
执行第二个脚本。去掉视频结尾17秒
import os
from moviepy.editor import VideoFileClip
def trim_video(file_path, output_path, duration_to_trim):
# 打开视频文件
clip = VideoFileClip(file_path)
# 获取视频总时长
video_duration = clip.duration
# 计算要删除的起始时间点,即视频总时长减去要删除的时长
start_trim_time = video_duration - duration_to_trim
# 截取视频,不包括最后10秒
if start_trim_time > 0:
clip_without_end = clip.subclip(0, start_trim_time)
else:
print("视频时长不足以删除10秒")
return
# 写入新视频
clip_without_end.write_videofile(output_path, codec='libx264')
# 关闭clip
clip_without_end.close()
clip.close()
def process_directory(directory):
# 遍历目录下的所有文件
for filename in os.listdir(directory):
if filename.endswith('.mp4'): # 假设视频文件是mp4格式
file_path = os.path.join(directory, filename)
output_path = os.path.join(directory, f"trimmed_{filename}")
# 定义要删除的时长为10秒
duration_to_trim = 17 # 10秒
# 处理视频
trim_video(file_path, output_path, duration_to_trim)
print(f"处理完成: {filename}")
# 指定视频文件所在的目录
directory_path = '.'
# 调用函数处理目录
process_directory(directory_path)