视频字幕1

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)

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值