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. 20165313Java实验四 Android程序设计

    实验报告封面 课程:Java程序设计 班级:1653班 姓名:张晨晖 学号:20165313 指导教师:娄嘉鹏 实验日期:2018年5月14日 实验时间:13:45 - 15:25 实验序号:实验四 ...

  2. 《DSP using MATLAB》Problem 5.37

    证明过程: 代码: %% +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ...

  3. Go Example--range

    package main import "fmt" func main() { nums := []int{2,3,4} sum :=0 //rang 遍历切片 for _,num ...

  4. torchvision库简介(翻译)

    部分跟新于:4.24日    torchvision 0.2.2.post3 torchvision是独立于pytorch的关于图像操作的一些方便工具库. torchvision的详细介绍在:http ...

  5. rsync入门使用

    rsync是用来同步文件的,但是是基于增量同步的,也就是说每次同步时不需要把全部文件数据都传输过去,只需要将不相同的部分(也就是说增量差异内容)传输过去. 其基本命令格式为rsync [option] ...

  6. 实现在同一界面打开putty终端连接工具

    用过putty的人可能知道,每打开一次啊putty程序只能开启一个连接,这个在实际运用中很不方便,反正我开ssh一般都是同时开四个窗口 其实有一个程序可以实现打开多个putty,下面是下载地址 htt ...

  7. 一不小心把win10的秘钥卸载了解决方法

    我遇到的第一个问题是Win10家庭版激活失败提示错误代码0xC004C003 然后我百度后看到一个解决方法是卸载秘钥然后再输入秘钥的,于是我执行了slmgr.vbs /upk,发现win10秘钥被卸载 ...

  8. JQuery城市选择

    <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...

  9. Avoiding post increase or decrease

    When we write a loop, most of us will use post increase or decrease, but there is a better solution. ...

  10. httpd

    http://httpd.apache.org/docs/2.2/logs.html httpd.conf文件 Configuration and logfile names: If the file ...