OCR定位图片中文字位置

简介

最近做自动化想着弄一个OCR识别点击的,做了调研,使用到了谷歌几年前的OCR框架以及百度飞浆的框架,最终选用百度飞浆,速度快,准确率高

import time
import cv2
from paddleocr import PaddleOCR
import logging


class MyOcr():
    def __init__(self, lang='ch'):
        log = logging.getLogger('ppocr')
        log.setLevel('ERROR')

        # 百度飞浆OCR  ocr_version="PP-OCR" 可选模型,当前用的是v3准确率最高
        self.ocr_v3 = PaddleOCR(use_gpu=False, lang=lang, ocr_version="PP-OCRv3", use_angle_cls=False, enable_mkldnn=True)

    def get_position_from_ocr_by_paddle(self, image_path, target_str, contains_flag=True):
        """
        从目标图片中查找目标文字的位置
        :param image_path: 待查找图片
        :param target_str: 待查找文字
        :param contains_flag: 默认是包含查找,因为ocr有时候会识别不太准确
        :return:
        """
        ocr = self.ocr_v3
        return_list = []
        start_time = time.time()

        # cv2
        img = cv2.imread(image_path, 0)

        result = ocr.ocr(img, cls=False)

        if contains_flag:
            for line in result:
                if target_str in line[-1][0]:
                    return_list.append(((line[0][0][0] + line[0][1][0]) / 2, (line[0][0][1] + line[0][2][1]) / 2))
        else:
            for line in result:
                if target_str == line[-1][0]:
                    return_list.append(((line[0][0][0] + line[0][1][0]) / 2, (line[0][0][1] + line[0][2][1]) / 2))
        return return_list

    def get_str(self, image_path, target_length=None):
        """
        根据图片解析图片中的文字,通常用作解验证码,仅在图片中找到一处文字时返回
        :param image_path: 图片地址
        :param target_length: 目标文字长度
        :return:
        """
        ocr = self.ocr_v3
        # cv2
        img = cv2.imread(image_path, 0)
        result = ocr.ocr(img, cls=False)
        if len(result) == 1:
            if target_length:
                return result[0][-1][0][-target_length:]
            else:
                return result[0][-1][0]
        else:
            return None

 

posted @ 2022-07-23 14:33  风,又奈何  阅读(885)  评论(0编辑  收藏  举报