建设维护网站 未签订合同互联网广告行业分析
一、简介
-
主要用于通过OCR(光学字符识别)在图像中查找特定文本,并绘制矩形框突出显示。旨在识别图像中的特定文本并标记其位置。。
代码包括:
-
OCRMatch类:用于初始化OCR引擎并查找文本坐标。
-
ocr_match函数:简化调用OCRMatch,查找文本坐标。
-
draw_rectangle函数:在图像上绘制矩形框并标记中心点。
-
-
存在潜在问题:边界框坐标提取可能不准确,建议优化为计算最小和最大x、y值以适应非轴对齐文本。
二、代码功能概述
1. OCRMatch类
OCRMatch
类是核心组件,用于初始化OCR引擎并执行文本匹配。其功能包括:
-
初始化: 设置OCR语言,默认俄语(‘ru’),支持中文(‘ch’)、英语(‘en’)等。
-
字符串比较:使用
difflib.SequenceMatcher
计算两个字符串的相似度,范围为0到1。 -
坐标查找: 通过OCR识别图像中的文本,过滤置信度低于0.75的结果,基于相似度阈值(默认0.8)返回匹配文本的坐标。
代码片段:
注意: PaddleOCR返回的边界框为四个点的坐标(x1, y1, x2, y2, x3, y3, x4, y4)
class OCRMatch:def __init__(self, ocr_language='ru'):self.ocr_language = ocr_languageself._ocr = PaddleOCR(use_angle_cls=True, lang=self.ocr_language)@staticmethoddef _compare_strings(str1, str2):seq_matcher = difflib.SequenceMatcher(None, str1, str2)return seq_matcher.ratio()def find_text_coordinates(self, image, text, threshold=0.8):result = self._ocr.ocr(image, cls=True)for idx in result[0]:if not isinstance(idx[1][0], str) and idx[1][1] < 0.75:continuesimilarity = self._compare_strings(idx[1][0], text)if similarity >= threshold:# 计算矩形对角点坐标x_coords = [idx[0][0], idx[0][2], idx[0][4], idx[0][6]]y_coords = [idx[0][1], idx[0][3], idx[0][5], idx[0][7]]x_min, x_max = min(x_coords), max(x_coords)y_min, y_max = 4. min(y_coords), max(y_coords)points = ((x_min, y_min), (x_max, y_max))conf = idx[1][1]return points, conf
2. ocr_match函数
ocr_matc
h函数是OCRMatch
类的包装,简化调用过程。它接受图像、目标文本、阈值和语言参数,返回匹配文本的坐标。
代码片段:
def ocr_match(image, text, threshold=0.8, language='ru'):points, conf = OCRMatch(language).find_text_coordinates(image, text, threshold)return points
3. draw_rectangle函数
draw_rectangle函数
用于在图像上绘制矩形框,标记文本位置,并计算并返回矩形中心点。它使用OpenCV加载图像,绘制矩形,并标记中心点。
代码片段:
def draw_rectangle(image_path, start_point, end_point, color=(0, 255, 0), thickness=2):image = cv2.imread(image_path)if image is None:raise ValueError(f"无法加载图片: {image_path}")cv2.rectangle(image, start_point, end_point, color, thickness)center_x = (start_point[0] + end_point[0]) // 2center_y = (start_point[1] + end_point[1]) // 2center_point = (center_x, center_y)return image, center_point
三、技术细节与分析
1. PaddleOCR与EasyOCR对比
-
EasyOCR:
简单易用,支持多语言,基于深度学习,安装命令为pip install easyocr。 -
PaddleOCR:
百度开源,支持中文,准确性高,安装命令为pip install paddlepaddle paddleocr。
2. 总结与建议
思路构建一个OCR框架,结合PaddleOCR的高准确性和字符串相似度匹配,实现在图像中查找并可视化特定文本