# OCR 方法与代码文档 本文档详细介绍了从PPT中提取视频截图并使用OCR识别标题的方法和代码实现。 ## 1. 技术栈概述 在本项目中,我们使用了以下技术和库: - **Python 3.10.12**:主要编程语言 - **python-pptx**:用于读取和处理PPT文件 - **Pillow (PIL)**:用于图像处理 - **pytesseract**:Python的Tesseract OCR包装器 - **Tesseract OCR**:开源OCR引擎 - **正则表达式 (re)**:用于文本清理和处理 ## 2. 环境设置 首先,我们安装了必要的依赖项: ```python # 安装Python库 pip3 install python-pptx pillow pytesseract # 安装Tesseract OCR引擎及中文语言包 sudo apt-get update && sudo apt-get install -y tesseract-ocr tesseract-ocr-chi-sim ``` ## 3. 从PPT提取图片 我们使用`python-pptx`库从PPT文件中提取图片: ```python def extract_images_from_slide(ppt_path, slide_index): """从指定幻灯片中提取所有图片""" prs = Presentation(ppt_path) if slide_index >= len(prs.slides): print(f"错误:幻灯片索引 {slide_index} 超出范围,PPT只有 {len(prs.slides)} 页") return [] slide = prs.slides[slide_index] images = [] # 提取幻灯片中的所有图片 for shape in slide.shapes: if hasattr(shape, "image"): # 获取图片数据 image_bytes = shape.image.blob # 使用PIL打开图片 img = Image.open(io.BytesIO(image_bytes)) # 保存图片信息 images.append({ 'image': img, 'width': shape.width, 'height': shape.height, 'left': shape.left, 'top': shape.top }) return images ``` 对于处理整个PPT的所有幻灯片,我们使用了类似的函数: ```python def extract_images_from_all_slides(ppt_path, output_dir): """从所有幻灯片中提取图片,并保存到指定目录""" prs = Presentation(ppt_path) # 确保输出目录存在 os.makedirs(output_dir, exist_ok=True) image_info = [] for slide_index, slide in enumerate(prs.slides): for shape_index, shape in enumerate(slide.shapes): if hasattr(shape, "image"): # 获取图片数据 image_bytes = shape.image.blob # 使用PIL打开图片 img = Image.open(io.BytesIO(image_bytes)) # 保存图片 img_path = f"{output_dir}/slide_{slide_index+1}_image_{shape_index+1}.png" img.save(img_path) # 记录图片信息 image_info.append({ 'slide_index': slide_index + 1, 'shape_index': shape_index + 1, 'image_path': img_path, 'width': shape.width, 'height': shape.height, 'left': shape.left, 'top': shape.top }) return image_info ``` ## 4. OCR文本识别 我们使用`pytesseract`库进行OCR文本识别,并指定使用中文和英文语言包: ```python def extract_title_from_image(image, lang='chi_sim+eng'): """使用OCR从图片中提取标题""" # 使用pytesseract进行OCR识别 text = pytesseract.image_to_string(image, lang=lang) return text.strip() ``` 关键参数说明: - `lang='chi_sim+eng'`:指定使用简体中文和英文语言包,这对于识别中英文混合的视频标题非常重要 ## 5. 文本清理与处理 OCR识别出的原始文本通常包含噪声和不需要的信息,我们使用两个函数进行清理: ```python def clean_title(title): """清理提取的标题文本""" # 移除多余的空白字符 title = re.sub(r'\s+', ' ', title) # 移除可能的视频时长、播放量等信息 title = re.sub(r'\d+:\d+', '', title) # 移除其他可能的干扰文本 title = re.sub(r'播放量.*?$', '', title, flags=re.MULTILINE) title = re.sub(r'弹幕.*?$', '', title, flags=re.MULTILINE) title = re.sub(r'投稿.*?$', '', title, flags=re.MULTILINE) return title.strip() def clean_title_for_search(title): """进一步清理标题,提取关键信息用于搜索""" # 移除日期、时间和统计信息 title = re.sub(r'\d{4}年\d{2}月\d{2}日.*?$', '', title, flags=re.MULTILINE) title = re.sub(r'当前字幕.*?$', '', title, flags=re.MULTILINE) title = re.sub(r'加 \d+.*?$', '', title, flags=re.MULTILINE) title = re.sub(r'回 \d+.*?$', '', title, flags=re.MULTILINE) title = re.sub(r'@.*?$', '', title, flags=re.MULTILINE) title = re.sub(r'th \d+.*?$', '', title, flags=re.MULTILINE) # 移除"活动"前缀和引号 title = re.sub(r'^活动\s*[\"《]', '', title) title = re.sub(r'^活动\s*', '', title) title = re.sub(r'[\"》]', '', title) # 移除省略号和后面的内容 title = re.sub(r'\.{3,}.*?$', '', title, flags=re.MULTILINE) title = re.sub(r'….*?$', '', title, flags=re.MULTILINE) # 移除多余空格 title = re.sub(r'\s+', ' ', title) return title.strip() ``` 这两个函数的主要目的是: 1. `clean_title`:移除基本的噪声,如多余空格、时长标记、播放量等 2. `clean_title_for_search`:进一步清理,提取最有用的搜索关键词,移除日期、时间、前缀等 ## 6. 搜索关键词提取 为了提高搜索效率,我们从清理后的标题中提取关键词: ```python def create_search_queries(titles_batch): """为每个标题创建搜索查询""" search_queries = [] for title in titles_batch: # 提取关键词 search_title = title['search_title'] keywords = [] # 如果标题包含"|",取"|"后面的部分作为关键词 if '|' in search_title: parts = search_title.split('|') for part in parts: part = part.strip() if len(part) >= 5: keywords.append(part) else: # 否则使用整个标题 keywords.append(search_title) # 为每个关键词创建搜索查询 for keyword in keywords: search_queries.append({ 'title_index': title['index'], 'original_title': title['original_title'], 'search_title': title['search_title'], 'keyword': keyword, 'query': f"课代表立正 {keyword}" }) return search_queries ``` 这个函数的关键点是: 1. 识别标题中的分隔符"|",将标题分成多个部分 2. 对每个部分进行长度检查,确保它足够有意义 3. 为每个有效的关键词创建搜索查询,添加"课代表立正"前缀 ## 7. 系统化的OCR处理流程 为了确保OCR处理的准确性和可追踪性,我们实现了一个系统化的处理流程: ```python def main(): # 文件路径 ppt_path = '/home/ubuntu/bilibili_project/第三部分.pptx' output_dir = '/home/ubuntu/bilibili_project/systematic_images' # 1. 提取幻灯片信息并创建摘要 print("正在提取幻灯片信息...") slide_info = extract_slide_info(ppt_path) create_slide_summary(slide_info) # 2. 提取所有图片 print("正在从幻灯片中提取图片...") image_info = extract_images_from_all_slides(ppt_path, output_dir) print(f"共提取了 {len(image_info)} 张图片") # 3. 从图片中提取标题 print("正在从图片中提取视频标题...") titles_info = extract_titles_from_images(image_info) create_titles_document(titles_info) print("系统化文档记录过程已完成") ``` 这个流程包括: 1. 提取幻灯片信息并创建摘要 2. 从所有幻灯片中提取图片 3. 使用OCR从图片中提取标题 4. 创建详细的文档记录每一步的结果 ## 8. 验证与质量控制 为了确保OCR结果的质量,我们实现了验证机制: ```python def verify_slide_counts(slide_info, titles_info): """验证每页的视频数量是否一致""" verification_results = [] # 按幻灯片页码分组 titles_by_slide = {} for title in titles_info: slide_num = title['slide_num'] if slide_num not in titles_by_slide: titles_by_slide[slide_num] = [] titles_by_slide[slide_num].append(title) # 验证每页的视频数量 for slide_num, expected_count in slide_info.items(): actual_count = len(titles_by_slide.get(slide_num, [])) is_valid = actual_count == expected_count verification_results.append({ 'slide_num': slide_num, 'expected_count': expected_count, 'actual_count': actual_count, 'is_valid': is_valid }) return verification_results ``` 我们还评估了视频标题的质量: ```python # 视频标题质量评估 content += "## 2. 视频标题质量评估\n\n" content += "| 页码 | 视频编号 | 搜索用文本长度 | 质量评估 |\n" content += "|------|----------|----------------|----------|\n" for title in titles_info: search_text_length = len(title['search_text']) if search_text_length < 5: quality = "❌ 低质量 (文本过短)" elif search_text_length < 10: quality = "⚠️ 中等质量" else: quality = "✅ 高质量" content += f"| {title['slide_num']} | {title['video_num']} | {search_text_length} | {quality} |\n" ``` ## 9. 最佳实践与经验教训 在OCR处理过程中,我们总结了以下最佳实践: 1. **使用多语言支持**:对于中英文混合的文本,使用`lang='chi_sim+eng'`参数 2. **分步清理文本**:先进行基本清理,再进行搜索优化清理 3. **利用标题结构**:识别分隔符如"|",提取更有意义的关键词 4. **系统化记录**:记录每一步的处理结果,便于追踪和验证 5. **质量评估**:对OCR结果进行质量评估,识别可能的问题 ## 10. 完整代码示例 以下是一个完整的OCR处理示例: ```python import os import re from pptx import Presentation from PIL import Image import pytesseract import io # 设置pytesseract使用中文语言包 pytesseract.pytesseract.tesseract_cmd = 'tesseract' def extract_images_from_slide(ppt_path, slide_index): """从指定幻灯片中提取所有图片""" prs = Presentation(ppt_path) if slide_index >= len(prs.slides): print(f"错误:幻灯片索引 {slide_index} 超出范围,PPT只有 {len(prs.slides)} 页") return [] slide = prs.slides[slide_index] images = [] # 提取幻灯片中的所有图片 for shape in slide.shapes: if hasattr(shape, "image"): # 获取图片数据 image_bytes = shape.image.blob # 使用PIL打开图片 img = Image.open(io.BytesIO(image_bytes)) # 保存图片信息 images.append({ 'image': img, 'width': shape.width, 'height': shape.height, 'left': shape.left, 'top': shape.top }) return images def extract_title_from_image(image, lang='chi_sim+eng'): """使用OCR从图片中提取标题""" # 使用pytesseract进行OCR识别 text = pytesseract.image_to_string(image, lang=lang) return text.strip() def clean_title(title): """清理提取的标题文本""" # 移除多余的空白字符 title = re.sub(r'\s+', ' ', title) # 移除可能的视频时长、播放量等信息 title = re.sub(r'\d+:\d+', '', title) # 移除其他可能的干扰文本 title = re.sub(r'播放量.*?$', '', title, flags=re.MULTILINE) title = re.sub(r'弹幕.*?$', '', title, flags=re.MULTILINE) title = re.sub(r'投稿.*?$', '', title, flags=re.MULTILINE) return title.strip() def clean_title_for_search(title): """进一步清理标题,提取关键信息用于搜索""" # 移除日期、时间和统计信息 title = re.sub(r'\d{4}年\d{2}月\d{2}日.*?$', '', title, flags=re.MULTILINE) title = re.sub(r'当前字幕.*?$', '', title, flags=re.MULTILINE) title = re.sub(r'加 \d+.*?$', '', title, flags=re.MULTILINE) title = re.sub(r'回 \d+.*?$', '', title, flags=re.MULTILINE) title = re.sub(r'@.*?$', '', title, flags=re.MULTILINE) title = re.sub(r'th \d+.*?$', '', title, flags=re.MULTILINE) # 移除"活动"前缀和引号 title = re.sub(r'^活动\s*[\"《]', '', title) title = re.sub(r'^活动\s*', '', title) title = re.sub(r'[\"》]', '', title) # 移除省略号和后面的内容 title = re.sub(r'\.{3,}.*?$', '', title, flags=re.MULTILINE) title = re.sub(r'….*?$', '', title, flags=re.MULTILINE) # 移除多余空格 title = re.sub(r'\s+', ' ', title) return title.strip() def main(): ppt_path = '/home/ubuntu/bilibili_project/第三部分.pptx' slide_index = 9 # 第10页的索引是9(从0开始计数) print(f"正在处理PPT第 {slide_index+1} 页...") # 提取图片 images = extract_images_from_slide(ppt_path, slide_index) print(f"从第 {slide_index+1} 页提取到 {len(images)} 张图片") # 保存图片并提取标题 os.makedirs('images', exist_ok=True) titles = [] for i, img_info in enumerate(images): # 保存图片 img_path = f"images/slide_{slide_index+1}_image_{i+1}.png" img_info['image'].save(img_path) # 提取标题 raw_title = extract_title_from_image(img_info['image']) clean_title_text = clean_title(raw_title) search_title = clean_title_for_search(clean_title_text) titles.append({ 'image_path': img_path, 'raw_title': raw_title, 'clean_title': clean_title_text, 'search_title': search_title }) print(f"图片 {i+1}:") print(f" 路径: {img_path}") print(f" 原始标题: {raw_title}") print(f" 清理后标题: {clean_title_text}") print(f" 搜索用标题: {search_title}") print("-" * 50) # 将标题保存到文件 with open('titles_page10.txt', 'w', encoding='utf-8') as f: for i, title_info in enumerate(titles): f.write(f"图片 {i+1}:\n") f.write(f" 路径: {title_info['image_path']}\n") f.write(f" 原始标题: {title_info['raw_title']}\n") f.write(f" 清理后标题: {title_info['clean_title']}\n") f.write(f" 搜索用标题: {title_info['search_title']}\n") f.write("-" * 50 + "\n") print(f"已将标题保存到 titles_page10.txt") if __name__ == "__main__": main() ``` ## 总结 本文档详细介绍了从PPT中提取视频截图并使用OCR识别标题的方法和代码实现。通过使用Python、pytesseract和相关库,我们实现了一个完整的OCR处理流程,包括图片提取、文本识别、清理处理和验证机制。这些方法和代码可以用于类似的OCR任务,特别是从PPT或其他文档中提取和识别文本内容。