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. Go Example--变量

    package main import "fmt" //通过import导入fmt标准包 func main() { //定义变量,并初始化 var a string = &quo ...

  2. 我的TDD实践---CI持续集成

    “我的TDD实践”系列之CI持续集成 写在前面: 我的TDD实践这几篇文章主要是围绕测试驱动开发所展开的,其中涵盖了一小部分测试理论,更多的则是关注工具的使用及环境的搭建,做到简单实践先行,后理论专精 ...

  3. 尚硅谷【SpringBoot】入门

    https://www.bilibili.com/video/av20965295/?p=2 缺点: 基于springframe的封装    对framework api需要熟悉 2微服务 2014 ...

  4. MySQL--派生表临时结果集中的AutoKey

    在某些场景中,需要对派生表生成临时结果集进行materialized,如果该临时结果集中包含索引键,那么查询有可能通过该索引键来进行优化. 如对下面查询: SELECT T2.purpose_code ...

  5. nginx与Apache的优缺点

    来源:http://itindex.net/detail/46414-apache-nginx 1.nginx相对于apache的优点: 轻量级,同样起web 服务,比apache 占用更少的内存及资 ...

  6. JSON字符串转C#实体Class类

    在项目开发过程中,经常需要和不同部门或者不同的组员一起协同工作,但对方写的json返回的结果集,我们需要用,那么如何来生成对应的类代码和实体对象呢?于是参考了网上的做法,做一个简单的字符串转实体类的功 ...

  7. MySQL中or与in

    and和or mysql允许多个where子句,用and和or可以使用多个子句.and比or有更高的优先级.任何时候使用and和or都应使用圆括号操作符来明确的分组操作. in 圆括号在where子句 ...

  8. Distributed processing

    Distributed processing Tool 好处 坏处 类型 支持序列化 支持根据负载动态调度任务 支持c 支持dependency的调度 有成熟的library Actor model ...

  9. egg 官方文档之:框架扩展(Application、Context、Request、Response、Helper的访问方式及扩展)

    地址:https://eggjs.org/zh-cn/basics/extend.html Application app 对象指的是 Koa 的全局应用对象,全局只有一个,在应用启动时被创建. 访问 ...

  10. C# 抽象类和密闭方法

    抽象类abstract: 1.抽象类只存在一个目的就是被继承:2.抽象类不能够实例化,只能够被继承:3.抽象类可以包含抽象成员和普通成员,以及他们的任意组合:4.抽象类的抽象成员在派生类中需要使用ov ...