本文共 4630 字,大约阅读时间需要 15 分钟。
本文将详细介绍如何利用 PaddleOCR 进行图片文字识别,并通过关键词定位实现自动化的图片标记与处理任务。我们将从 OCR 模型的初始化、关键词匹配的逻辑设计,以及最终的图片标记与保存环节,全面阐述实现过程。
在实际应用中,首先需要初始化 PaddleOCR 模型,并选择合适的语言模型。以下是具体的实现代码:
from paddleocr import PaddleOCRimport cv2import numpy as npimport osfrom datetime import datetimeimport pytz# 初始化PaddleOCR,使用中文模型ocr = PaddleOCR(use_angle_cls=True, lang="ch")
首先,我们从 OCR 识别结果中提取所有单词及其对应的坐标信息。然后,基于关键词进行完整匹配:
# 提取所有单词和坐标信息word_boxes = []for line in result: for word_info in line: word = word_info[1][0] processed_word = word.replace("?", "") points = word_info[0] points_list = [[int(p[0]), int(p[1])] for p in points] word_dict = { 'word': word, 'processed_word': processed_word, 'points': points_list } word_boxes.append(word_dict) 对于不完全匹配的情况,我们需要考虑关键词被分成两部分的情况。具体实现如下:
# 查找可能的部分匹配(关键词被分成两部分的情况)partial_matches = []for i, box in enumerate(word_boxes): if i not in processed_indices and box['processed_word'] in keyword: partial_matches.append((i, box))# 尝试找出可以组合成完整关键词的两部分for i in range(len(partial_matches)): idx1, box1 = partial_matches[i] if idx1 in processed_indices: continue for j in range(i + 1, len(partial_matches)): idx2, box2 = partial_matches[j] if idx2 in processed_indices: continue combined = box1['processed_word'] + box2['processed_word'] reversed_combined = box2['processed_word'] + box1['processed_word'] if combined == keyword or reversed_combined == keyword: if is_same_line(box1, box2): # 确定左右顺序 if box1['points'][0][0] < box2['points'][0][0]: left_box, right_box = box1, box2 else: left_box, right_box = box2, box1 merged_points = merge_boxes(left_box, right_box) keyword_boxes.append({ 'keyword': keyword, 'merged': True, 'points': merged_points, 'parts': [left_box['processed_word'], right_box['processed_word']] }) # 标记这两个box为已处理 processed_indices.add(idx1) processed_indices.add(idx2) break # 找到一个匹配后就跳出内层循环 在实际应用中,我们需要将找到的关键词位置绘制到图片上,并进行标记。以下是具体实现:
# 使用cv2.imdecode读取图片img = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), cv2.IMREAD_COLOR)if img is None: raise ValueError("无法读取图像文件,可能已损坏或不支持的格式")# 为每个找到的位置绘制边界框for box in keyword_boxes: points = np.array(box['points'], dtype=np.int32) cv2.polylines(img, [points], isClosed=True, color=(0, 255, 0), thickness=2) label = f"{keyword} {'(merged)' if box['merged'] else ''}" cv2.putText(img, label, (points[0][0], points[0][1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2) 最后,我们将处理后的图片保存到指定路径:
# 处理输出路径output_dir = os.path.dirname(image_path)shanghai_tz = pytz.timezone('Asia/Shanghai')current_time = datetime.now(shanghai_tz).strftime("%Y%m%d_%H%M%S")filename = f"-{current_time}-marked-{keyword}.png"output_name = os.path.basename(image_path).replace('.png', filename)output_path = os.path.join(output_dir, output_name)# 使用cv2.imencode保存图片success, buf = cv2.imencode('.png', img)if success: with open(output_path, 'wb') as f: f.write(buf) print(f"标记结果已保存至: {output_path}")else: raise RuntimeError("图像保存失败") 将以上各个环节整合,形成完整的处理流程:
def process_image_with_keyword(image_path, keyword): cleaned_keyword = keyword.replace("@", "") try: keyword_boxes = find_keyword_boxes(image_path, cleaned_keyword) print(f"在图片中找到 '{cleaned_keyword}' 的位置:") for i, box in enumerate(keyword_boxes, 1): print(f"\n位置 {i}:") if box['merged']: print(f"由部分合并: {' + '.join(box['parts'])}") print(f"坐标: {box['points']}") if not keyword_boxes: print(f"未在图片中找到关键词 '{cleaned_keyword}'") return None return draw_and_save_boxes(image_path, keyword_boxes, cleaned_keyword) except Exception as e: print(f"处理图片时发生错误: {str(e)}") return None # 使用示例image_path = r'C:\Leon\python_project\oceanxecm\2025\04\20250410-Logan-ocr位置\png\SWC22551 NT水光瓶2.5包装设计V1-250305. OL_545_1.0.png'keyword = "斯维诗@透明质酸钠胶原蛋白三肽饮料"result_path = process_image_with_keyword(image_path, keyword)if result_path: print(f"处理完成,结果保存在: {result_path}") 通过以上实现,我们可以高效地利用 PaddleOCR 进行图片文字识别,并通过关键词定位实现自动化的图片标记与处理任务。
转载地址:http://qoqfk.baihongyu.com/