查找关键词在图片中的坐标位置
·
查找关键词在图片中的坐标位置
要解决这个问题,我们需要使用OCR(光学字符识别)技术来识别图片中的文本并定位特定关键词的位置。我将提供Python解决方案,使用Pytesseract(基于Tesseract OCR引擎)和OpenCV来实现。
Python解决方案
import cv2
import pytesseract
from pytesseract import Output
import re
def find_keyword_positions(image_path, keyword):
# 读取图片
img = cv2.imread(image_path)
# 使用pytesseract获取所有文本及其位置信息
d = pytesseract.image_to_data(img, output_type=Output.DICT, lang='chi_sim+eng')
# 准备正则表达式,处理®符号和可能的换行
# 将®替换为可能的OCR识别结果(可能被识别为R等)
keyword_pattern = keyword.replace('®', '[®R]').replace(' ', r'\s*')
keyword_pattern = re.sub(r'([^\w\s®R])', r'\\\1', keyword_pattern)
# 获取所有文本块
n_boxes = len(d['level'])
text_blocks = []
for i in range(n_boxes):
if int(d['conf'][i]) > 30: # 只考虑置信度较高的识别结果
(x, y, w, h) = (d['left'][i], d['top'][i], d['width'][i], d['height'][i])
text = d['text'][i]
text_blocks.append({'x': x, 'y': y, 'w': w, 'h': h, 'text': text})
# 合并相邻的文本块(处理换行情况)
merged_blocks = []
i = 0
while i < len(text_blocks):
current = text_blocks[i]
j = i + 1
while j < len(text_blocks):
next_block = text_blocks[j]
# 检查是否在同一行或垂直接近
if (abs(current['y'] - next_block['y']) < current['h']/2 or
abs((current['y'] + current['h']) - (next_block['y'] + next_block['h'])) < current['h']/2):
# 合并文本
current['text'] += ' ' + next_block['text']
# 扩展边界框
current['x'] = min(current['x'], next_block['x'])
current['y'] = min(current['y'], next_block['y'])
current['w'] = max(current['x'] + current['w'], next_block['x'] + next_block['w']) - current['x']
current['h'] = max(current['y'] + current['h'], next_block['y'] + next_block['h']) - current['y']
j += 1
else:
break
merged_blocks.append(current)
i = j
# 搜索关键词
matches = []
for block in merged_blocks:
if re.search(keyword_pattern, block['text'], re.IGNORECASE):
# 获取边界框坐标
x1 = block['x']
y1 = block['y']
x2 = x1 + block['w']
y2 = y1 + block['h']
matches.append(((x1, y1), (x2, y2), 'text': block['text']))
return matches
# 使用示例
image_path = 'SWC22551_NT水光瓶2.5包装设计V1-250305_OL_545_1.0.png'
keyword = '斯维诗®透明质酸钠胶原蛋白三肽饮料'
matches = find_keyword_positions(image_path, keyword)
for i, match in enumerate(matches, 1):
(x1, y1), (x2, y2), text = match
print(f"匹配 {i}:")
print(f"文本: {text}")
print(f"左上角坐标: ({x1}, {y1})")
print(f"右下角坐标: ({x2}, {y2})")
print("-" * 50)
代码说明
- OCR处理: 使用Pytesseract进行OCR识别,获取文本及其位置信息。
- 特殊字符处理: 将®符号处理为正则表达式模式,考虑它可能被识别为R或其他字符。
- 多行文本合并: 通过检查文本块的垂直位置,将可能是同一段文本的多个块合并。
- 关键词搜索: 使用正则表达式搜索合并后的文本块,找到包含关键词的块。
- 坐标返回: 返回每个匹配项的左上角和右下角坐标。
注意事项
-
需要先安装Tesseract OCR和Pytesseract:
pip install pytesseract opencv-python并下载中文语言包。
-
对于®符号,OCR可能识别为R或其他字符,所以正则表达式做了相应处理。
-
如果图片质量不高,可能需要先进行预处理(如二值化、降噪等)。
-
对于复杂的包装设计,可能需要调整合并文本块的阈值参数。
这个解决方案应该能够处理您描述的问题,包括特殊字符和多行文本的情况。
更多推荐



所有评论(0)