import cv2
import pytesseract
from PIL import Image
import os
# 确保 Tesseract OCR 已安装并且配置好
# 在 Kaggle 中,Tesseract 已预先安装,不需要设置路径
# 视频路径
video_path = '/kaggle/input/202408282/vv1.mp4' # 请替换为你的视频文件路径
output_dir = '/kaggle/working/captured_frames'
os.makedirs(output_dir, exist_ok=True)
def extract_subtitle_text(frame, subtitle_region):
"""提取帧中指定区域的字幕文本"""
x, y, w, h = subtitle_region
cropped_frame = frame[y:y+h, x:x+w]
gray = cv2.cvtColor(cropped_frame, cv2.COLOR_BGR2GRAY)
# 使用 Tesseract 识别字幕
text = pytesseract.image_to_string(gray, lang='eng') # 根据实际字幕语言选择语言
return text.strip()
def save_frame(frame, count):
"""保存当前帧为图像文件"""
img = Image.fromarray(frame)
img.save(os.path.join(output_dir, f'frame_{count}.png'))
def capture_frames_with_subtitles(video_path, subtitle_region):
cap = cv2.VideoCapture(video_path)
prev_text = ""
count = 0
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# 提取当前帧中的字幕文本
current_text = extract_subtitle_text(frame, subtitle_region)
# 检测到字幕发生变化,保存帧
if current_text and current_text != prev_text:
print(f"Detected new subtitle: {current_text}")
save_frame(frame, count)
count += 1
prev_text = current_text
cap.release()
print(f"Finished processing. Total frames captured: {count}")
# 设置字幕区域 (根据实际视频的字幕位置调整)
# 请根据视频中字幕的实际位置和大小调整参数
subtitle_region = (260,710,940,70) # x, y, width, height
# 运行程序
capture_frames_with_subtitles(video_path, subtitle_region)
视频字幕1
最新推荐文章于 2024-09-03 23:35:54 发布