博客
关于我
04-paddleocr_keyword_marker
阅读量:800 次
发布时间:2023-03-23

本文共 4630 字,大约阅读时间需要 15 分钟。

使用 PaddleOCR 进行图片文字识别与关键词定位的实用解决方案

本文将详细介绍如何利用 PaddleOCR 进行图片文字识别,并通过关键词定位实现自动化的图片标记与处理任务。我们将从 OCR 模型的初始化、关键词匹配的逻辑设计,以及最终的图片标记与保存环节,全面阐述实现过程。

1. OCR 模型的初始化

在实际应用中,首先需要初始化 PaddleOCR 模型,并选择合适的语言模型。以下是具体的实现代码:

from paddleocr import PaddleOCR
import cv2
import numpy as np
import os
from datetime import datetime
import pytz
# 初始化PaddleOCR,使用中文模型
ocr = PaddleOCR(use_angle_cls=True, lang="ch")

2. 关键词匹配的逻辑设计

2.1 完整匹配逻辑

首先,我们从 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)

2.2 部分匹配逻辑

对于不完全匹配的情况,我们需要考虑关键词被分成两部分的情况。具体实现如下:

# 查找可能的部分匹配(关键词被分成两部分的情况)
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 # 找到一个匹配后就跳出内层循环

3. 图片标记与结果保存

3.1 绘制框架

在实际应用中,我们需要将找到的关键词位置绘制到图片上,并进行标记。以下是具体实现:

# 使用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)

3.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("图像保存失败")

4. 整体流程实现

将以上各个环节整合,形成完整的处理流程:

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

5. 使用示例

# 使用示例
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/

你可能感兴趣的文章
Objective-C实现图像去雾算法(附完整源码)
查看>>
Objective-C实现图像灰度变换(附完整源码)
查看>>
Objective-C实现图像移动(附完整源码)
查看>>
Objective-C实现图层混合算法(附完整源码)
查看>>
Objective-C实现图片erosion operation侵蚀操作算法(附完整源码)
查看>>
Objective-C实现图片的放大缩小(附完整源码)
查看>>
Objective-C实现图片腐蚀(附完整源码)
查看>>
Objective-C实现图片膨胀(附完整源码)
查看>>
Objective-C实现图的邻接矩阵(附完整源码)
查看>>
Objective-C实现圆球的表面积和体积(附完整源码)
查看>>
Objective-C实现在Regex的帮助下检查字谜算法(附完整源码)
查看>>
Objective-C实现均值滤波(附完整源码)
查看>>
Objective-C实现埃拉托斯特尼筛法算法(附完整源码)
查看>>
Objective-C实现域名解析(附完整源码)
查看>>
Objective-C实现域名转IP(附完整源码)
查看>>
Objective-C实现培根密码算法(附完整源码)
查看>>
Objective-C实现基于 LIFO的堆栈算法(附完整源码)
查看>>
Objective-C实现基于 LinkedList 的添加两个数字的解决方案算法(附完整源码)
查看>>
Objective-C实现基于opencv的抖动算法(附完整源码)
查看>>
Objective-C实现基于事件对象实现线程同步(附完整源码)
查看>>