OpenCv pytesseract for OCR

时间:2016-07-02 11:26:58

标签: python opencv

如何使用opencv和pytesseract从图像中提取文本?

import cv2

导入pytesseract 来自PIL导入图片 导入numpy为np 从matplotlib导入pyplot作为plt

img = Image.open('test.jpg').convert('L')
img.show()
img.save('test','png')
img = cv2.imread('test.png',0)
edges = cv2.Canny(img,100,200)
#contour = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
#print pytesseract.image_to_string(Image.open(edges))
print pytesseract.image_to_string(edges)

但这是错误的 -

追踪(最近一次通话):   文件“open.py”,第14行,in     print pytesseract.image_to_string(edges)   在image_to_string中输入文件“/home/sroy8091/.local/lib/python2.7/site-packages/pytesseract/pytesseract.py”,第143行     如果len(image.split())== 4: AttributeError:'NoneType'对象没有属性'split'

2 个答案:

答案 0 :(得分:5)

如果你想使用opencv进行一些预处理(就像你做了一些边缘检测),如果你想提取文本,你可以使用这个命令,

# All the imports and other stuffs goes here
img = cv2.imread('test.png',0)
edges = cv2.Canny(img,100,200)
img_new = Image.fromarray(edges)
text = pytesseract.image_to_string(img_new, lang='eng')
print (text)

答案 1 :(得分:0)

您无法直接将Opencv对象与tesseract方法一起使用。

尝试:

from PIL import Image
from pytesseract import *

image_file = 'test.png'
print(pytesseract.image_to_string(Image.open(image_file)))