ocr 文字区域检测及识别

# coding=utf-

from PIL import Image, ImageFilter, ImageEnhance
from skimage.filters import threshold_otsu
import skimage.morphology as sm
from skimage.measure import regionprops
import matplotlib.pyplot as plt
import numpy as np
import pytesseract
import re
import os
import time
import logging
logging.basicConfig(level=logging.INFO, format="%(message)s", filename='train_output.log') class ShopCert(object):
def cut_region(self, img):
"""
先按规则缩小搜索范围
"""
w, h = img.size
if h<:
factor = max(, 1600.0/h)
newsize = int(w*factor), int(h*factor)
img = img.resize(newsize, Image.ANTIALIAS)
if w<h:
box = (w*0.4, h*0.18, w*0.96, h*0.6)
else:
box = (w*0.1, h*0.18, w*0.96, h*0.9)
return img.crop(box) def detect_text(self, img):
"""
检测字符区域
"""
imgM = np.array(img.convert('L'))
imgM = * (imgM < threshold_otsu(imgM))
imgM = sm.binary_closing(imgM, np.ones((, )))
imgM = sm.remove_small_objects(imgM, )
label_img = sm.label(imgM)
imgList = []
for region in regionprops(label_img):
minr, minc, maxr, maxc = region.bbox
w, h = (maxc-minc), (maxr-minr)
if h > w * 0.2:
continue
box = minc-, minr-, maxc+, maxr+
imgList.append(img.crop(box))
return imgList def clear_noise(self, box):
"""
降噪处理
"""
box = box.convert('L')
# box = box.point(lambda x: if x< else x)
box = box.point(lambda x: if x> else x)
box = ImageEnhance.Contrast(box).enhance(2.5)
return box def predict(self, fname, lang='eng'):
"""
ocr 识别
"""
img = Image.open(fname)
# 先大致缩小范围
region = self.cut_region(img)
# 候选字符区域
# region = self.clear_noise(region)
boxList = self.detect_text(region)
# 遍历识别
for box in boxList:
box = self.clear_noise(box)
w, h = box.size
if float(w)/h > 12.5:
res = pytesseract.image_to_string(box, lang='chi_sim', config='-psm 7')
else:
res = pytesseract.image_to_string(box, lang='eng', config='-psm 7')
res = re.sub('\s', '', res) # 去除中间空白
res = re.findall(r'[0-9][A-Z0-9]{13,20}', res) # -20位
for line in res:
line = line.strip()
if line.find(u'年')>:
continue
print 'line', line
if len(line)> :
box.save('img/clearNoise/%s_%s.jpg' % (fname.split('/')[-].split('.')[], line))
return line
else:
print 'error line', line
return 'error' def show_pic(path='img/origin2/'):
fnames = [os.path.join(path, fname) for fname in os.listdir(path)]
for i, fname in enumerate(fnames, ):
print fname
img = Image.open(fname)
# img.save('./tesseract-train/cert.normal.exp%d.ttf' % i)
img = ImageEnhance.Contrast(img).enhance(2.0)
img = img.filter(ImageFilter.MedianFilter).convert('L')
plt.figure(figsize=(, ), dpi=)
plt.imshow(img, plt.cm.gray)
plt.title(fname.split('/')[-]+'_%d' % i)
plt.show()if __name__ == '__main__':
test = ShopCert()
path = 'img/origin2/'
fnames = [os.path.join(path, fname) for fname in os.listdir(path) if fname.endswith('jpg')]
fnames.sort() arguments = 'mode: L; enhance:2.0; h:0.5; dh:0.15'
logging.info('%s' % arguments)
logging.info("%s: %s" % ('imgname', 'result'))
start_time = time.time()
cnt =
for idx, fname in enumerate(fnames, ):
print idx, fname
y_true = fname.split('/')[-].split('_')[]
y_pred = test.predict(fname)
if y_true == y_pred:
cnt +=
print fname
else:
print '***'*
print 'error'
logging.info("%s: %s" % (fname, y_pred))
print 'y_true', y_true
print 'y_pred', y_pred
acc = float(cnt)/idx
print acc, cnt
print '=='*, idx
logging.info('%.3f %d/%d' % (acc, cnt, idx))
print 'cost time: ', time.time()-start_time
logging.info('accuracy: %.2f' % acc)

ocr 文字区域检测及识别的更多相关文章

  1. 王晶:华为云OCR文字识别服务技术实践、底层框架及应用场景 | AI ProCon 2019

    演讲嘉宾 | 王晶(华为云人工智能高级算法工程师王晶) 出品 | AI科技大本营(ID:rgznai100) 近期,由 CSDN 主办的 2019 中国AI 开发者大会(AI ProCon 2019) ...

  2. OCR文字识别在计算机视觉的重要性、基本技术和最新进展

    [摘要] 主要是文字检测和文字识别作为计算机视觉一部分的重要性,基本知识,面临的挑战,以及部分最新的成果. 人类认识了解世界的信息中91%来自视觉,同样计算机视觉成为机器认知世界的基础,也是人工智能研 ...

  3. OpenCV入门笔记(七) 文字区域的提取

    https://blog.csdn.net/huobanjishijian/article/details/63685503 前面我们已经学了一些OpenCV中基本的图片处理的知识,可以拿来做一些小应 ...

  4. 使用Python基于VGG/CTPN/CRNN的自然场景文字方向检测/区域检测/不定长OCR识别

    GitHub:https://github.com/pengcao/chinese_ocr https://github.com/xiaofengShi/CHINESE-OCR |-angle 基于V ...

  5. 云+社区分享——腾讯云OCR文字识别

    欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 本文由云+社区运营团队发布在腾讯云+社区 前言 2018年3月27日腾讯云云+社区联合腾讯云智能图像团队共同在客户群举办了腾讯云OCR文字识 ...

  6. 如何精准实现OCR文字识别?

    欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 本文由云计算基础发表于云+社区专栏 前言 2018年3月27日腾讯云云+社区联合腾讯云智能图像团队共同在客户群举办了腾讯云OCR文字识别-- ...

  7. OCR文字识别笔记总结

    OCR的全称是Optical Character Recognition,光学字符识别技术.目前应用于各个领域方向,甚至这些应用就在我们的身边,比如身份证的识别,交通路牌的识别,车牌的自动识别等等.本 ...

  8. 对OCR文字识别软件的扫描选项怎么设置

    说到OCR文字识别软件,越来越多的人选择使用ABBYY FineReader识别和转换文档,然而并不是每个人都知道转换质量取决于源图像的质量和所选的扫描选项,今天就给大家普及一下这方面的知识. ABB ...

  9. 怎么提高OCR文字识别软件的识别正确率

    在OCR文字识别软件当中,ABBYY FineReader是比较好用的程序之一,但再好的识别软件也不能保证100%的识别正确率,用户都喜欢软件的正确率高一些,以减轻识别后修正的负担,很多用户也都提过这 ...

随机推荐

  1. js framework comparation

    starting a new project:(finance project for p2p -- like lending club, or prosper ) ,we considering a ...

  2. AangularJS入门总结二

    双向数据绑定:在Mode(JS)中改变数据,而这些变动立刻就会自动出现在View上,反之亦然.一方面可以做到model变化驱动了DOM中元素变化,另一方面也可以做到DOM元素的变化也会影响到Model ...

  3. JS push对象

    var zoom = page.maps.maps._map.getZoom(), centerPoint = page.maps.maps._map.getCenter(); data = $(&q ...

  4. day29akka

    PS:AKKA之前要实现并发编程,通常要借用netty框架,现在如果又要高并发又要分布式就使用akka框架这个akka在客户端和服务端每一端都相当于一个actor,尤其是服务端需要一个总管进行管理 P ...

  5. golang for 循环变量取内存地址

    前几天提交的代码进行测试的时候发现变量无法赋值,原始代码如下: for _, asset := range dspInfo.native.Assets { var resAsset protocol. ...

  6. Spring事务管理机制的实现原理-动态代理

    之前在做项目中遇到spring无法进行事务代理问题,最后发现是因为没有写接口,原因当时明白了,看到这篇文章写的清楚些,转过来 我们先来分析一下Spring事务管理机制的实现原理.由于Spring内置A ...

  7. JavaScript Constructor & prototype

    阮一峰 JavaScript OOD 三部曲: 封装 JS 是一种基于对象(object-based)的语言. 但是JS不是一种真正的OOP语言, 因为语法中没有class. 以下就是简单的封装. 把 ...

  8. Spring Boot 历史

    2012年10月,Mike Youngstrom在Spring jira中创建了一个功能需求,要求在Spring框架中支持无容器Web应用程序体系结构.他建议通过main方法引导的Spring容器内配 ...

  9. 谈谈在 .Net 平台上的 软件生态 和 软件生产力

    我们可以先看看这篇文章 : <看 StackOverflow 如何用 25 台服务器撑起 5.6 亿的月 PV>    http://www.nowamagic.net/librarys/ ...

  10. thinkphp5 列表页数据分页查询2-带搜索条件

    一.控制器部分 <?php namespace app\user\controller; use app\index\controller\Common; use app\user\model\ ...