Python识别图片指定区域文字内容

Python批量识别图片指定区域文字内容

简介

对于一张图片,需求识别指定区域的内容

  1. 截取原始图上的指定图片当做模板
  2. 根据模板相似度去再原始图片上识别准确坐标
  3. 根据坐标剪切出指定位置图片,也就是所需的内容区域
  4. 对指定位置图片进行ocr识别

环境
Ubuntu18.04
Python2.7

所需Python模块

  1. aircv

    用于识别模板再原始图的位置坐标

pip install aircv
  1. Pillow
    用于剪裁图片
pip install Pillow
  1. Tesseract
    文字识别
    在此也可以用平台端的API进行更精准的识别
    ubuntu下Tesseract环境安装
    
    sudo apt-get install libpng12-dev 
    sudo apt-get install libjpeg62-dev 
    sudo apt-get install libtiff4-dev 
    sudo apt-get install gcc 
    sudo apt-get install g++ 
    sudo apt-get install automake

1.tesseract-ocr安装

sudo apt-get install tesseract-ocr

2.pytesseract安装

pip install pytesseract

Python代码

识别对应位置

#!/usr/bin/python2.7  
# -*- coding: utf-8 -*- 
import aircv


def matchImg(imgsrc, imgobj, confidence=0.2):
    """
        图片对比识别imgobj在imgsrc上的相对位置(批量识别统一图片中需要的部分)
    :param imgsrc: 原始图片路径(str)
    :param imgobj: 待查找图片路径(模板)(str)
    :param confidence: 识别度(0<confidence<1.0)
    :return: None or dict({'confidence': 相似度(float), 'rectangle': 原始图片上的矩形坐标(tuple), 'result': 中心坐标(tuple)})
    """
    imsrc = aircv.imread(imgsrc)
    imobj = aircv.imread(imgobj)

    match_result = aircv.find_template(imsrc, imobj,
                                    confidence)  # {'confidence': 0.5435812473297119, 'rectangle': ((394, 384), (394, 416), (450, 384), (450, 416)), 'result': (422.0, 400.0)}
    if match_result is not None:
        match_result['shape'] = (imsrc.shape[1], imsrc.shape[0])  # 0为高,1为宽

    return match_result

图片剪裁

#!/usr/bin/python2.7  
# -*- coding: utf-8 -*- 
from PIL import Image, ImageEnhance

def cutImg(imgsrc, out_img_name, coordinate):
    """
        根据坐标位置剪切图片
    :param imgsrc: 原始图片路径(str)
    :param out_img_name: 剪切输出图片路径(str)
    :param coordinate: 原始图片上的坐标(tuple) egg:(x, y, w, h) ---> x,y为矩形左上角坐标, w,h为右下角坐标
    :return:
    """
    image = Image.open(imgsrc)
    region = image.crop(coordinate)
    region = ImageEnhance.Contrast(region).enhance(1.5)
    region.save(out_img_name)

图片识别

#!/usr/bin/python2.7  
# -*- coding: utf-8 -*- 
import pytesseract
from PIL import Image

image = Image.open('bb.png')
code = pytesseract.image_to_string(image)
print(code)

对于三方API识别自行研究

————————————————
版权声明:本文为CSDN博主「Likeob」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_41616397/article/details/87980510

  • 15
    点赞
  • 146
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Likeob

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值