Python实现图片指定区域文字批量识别教程

Dylan
Dylan
发布时间:2026-10-12 | 2人浏览过
原创

本文介绍使用Python批量识别图片指定区域文字的方法。通过aircv进行模板匹配定位坐标,利用Pillow裁剪目标区域,最后调用Tesseract或第三方API进行OCR识别。文章提供了Ubuntu环境下的模块安装步骤及完整的Python代码示例,适用于批量处理图片中的特定文字内容。

本文介绍如何使用Python批量识别图片中指定区域的文字内容,供读者参考。

简介

主要需求是对单张图片进行指定区域的文字内容识别。

实现步骤如下: 1. 从原始图片中截取指定区域作为模板。 2. 根据模板相似度在原始图片中识别并确定准确坐标。 3. 根据获取的坐标剪切出指定位置图片,即所需内容区域。 4. 对剪切出的指定位置图片进行OCR识别。

环境

Ubuntu 18.04 Python 2.7

所需Python模块

1. aircv

用于识别模板在原始图中的位置坐标。

pip install aircv

2. Pillow

用于剪裁图片。

pip install Pillow

3. Tesseract

用于文字识别。 在此也可以使用平台端的API进行更精准的识别。

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

在Ubuntu下安装Tesseract环境的步骤如下: 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的识别方式,读者可自行研究。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表