温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何实现Opencv图片的OCR识别

发布时间:2021-03-02 14:10:18 来源:亿速云 阅读:797 作者:小新 栏目:开发技术

小编给大家分享一下如何实现Opencv图片的OCR识别,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

一、图片变换

0、导入模块

导入相关函数,遇到报错的话,直接pip install 函数名。

import numpy as np
import argparse
import cv2

参数初始化

ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required = True,
  help = "Path to the image to be scanned") 
args = vars(ap.parse_args())

Parameters:

--image images\page.jpg

1、重写resize函数

def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
  dim = None
  (h, w) = image.shape[:2]
  if width is None and height is None:
   return image
  if width is None:
   r = height / float(h)
   dim = (int(w * r), height)
  else:
   r = width / float(w)
   dim = (width, int(h * r))
  resized = cv2.resize(image, dim, interpolation=inter)
  return resized

2、预处理

读取图片后进行重置大小,并计算缩放倍数;进行灰度化、高斯滤波以及Canny轮廓提取

image = cv2.imread(args["image"])
ratio = image.shape[0] / 500.0
orig = image.copy()
image = resize(orig, height = 500)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(gray, 75, 200)

3、边缘检测

检测轮廓并排序,遍历轮廓。

cnts = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)[0]# 轮廓检测
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:5]#保留前5个轮廓

# 遍历轮廓
for c in cnts:
  # 计算轮廓近似
  peri = cv2.arcLength(c, True)# 计算轮廓长度,C表示输入的点集,True表示轮廓是封闭的
  #(C表示输入的点集,epslion判断点到相对应的line segment 的距离的阈值,曲线是否闭合的标志位)
  approx = cv2.approxPolyDP(c, 0.02 * peri, True)

  # 4个点的时候就拿出来
  if len(approx) == 4:
   screenCnt = approx
   break

4、透视变换

画出近似轮廓,透视变换,二值处理

cv2.drawContours(image, [screenCnt], -1, (0, 255, 0), 2)
warped = four_point_transform(orig, screenCnt.reshape(4, 2) * ratio)#透视变换

# 二值处理
warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY)
ref = cv2.threshold(warped, 100, 255, cv2.THRESH_BINARY)[1]
cv2.imwrite('scan.jpg', ref)

二、OCR识别

0、安装tesseract-ocr

链接: 下载

在环境变量、系统变量的Path里面添加安装路径,例如:E:\Program Files (x86)\Tesseract-OCR

tesseract -v#打开命令行,进行测试
tesseract XXX.png result#得到结果 
pip install pytesseract#安装依赖包

打开python安装路径里面的python文件,例如C:\ProgramData\Anaconda3\Lib\site-packages\pytesseract\pytesseract.py
将tesseract_cmd 修改为绝对路径即可,例如:tesseract_cmd = ‘C:/Program Files (x86)/Tesseract-OCR/tesseract.exe'

1、导入模块

from PIL import Image
import pytesseract
import cv2
import os

2、预处理

读取图片、灰度化、滤波

image = cv2.imread('scan.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.medianBlur(gray, 3)

3、输出结果

filename = "{}.png".format(os.getpid())
cv2.imwrite(filename, gray)  
text = pytesseract.image_to_string(Image.open(filename))
print(text)
os.remove(filename)

以上是“如何实现Opencv图片的OCR识别”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI