KeyError:使用 pytesseract.image_to_data 时出现“PNG”

Dan*_*nny 2 python ocr python-tesseract google-colaboratory

我尝试使用 pytesseract function 在图像文件中的文本周围放置方框image_to_data,但在 colab 上遇到以下错误:

    KeyError                                  Traceback (most recent call last)
<ipython-input-10-a92a28892aac> in <module>()
      6 img = cv2.imread("a.jpg")
      7 
----> 8 d = pytesseract.image_to_data(img, output_type=Output.DICT)
      9 print(d.keys())

5 frames
/usr/local/lib/python3.7/dist-packages/PIL/Image.py in save(self, fp, format, **params)
   2121         expand=0,
   2122         center=None,
-> 2123         translate=None,
   2124         fillcolor=None,
   2125     ):

KeyError: 'PNG'
Run Code Online (Sandbox Code Playgroud)

我正在使用的代码是:

import cv2
import pytesseract
from pytesseract import Output
from PIL import Image

img = cv2.imread("a.jpg")

d = pytesseract.image_to_data(img, output_type=Output.DICT)
print(d.keys())
Run Code Online (Sandbox Code Playgroud)

考虑到可能image_to_data只能使用 PNG 而不能使用 jpeg (这很奇怪),我添加了几行来将 jpeg 更改为 png,然后再输入到image_to_data,但同样的错误仍然存​​在。为什么会发生这种情况?

小智 5

在colab中,通过以下代码安装tesseract

!sudo apt-get install tesseract-ocr
Run Code Online (Sandbox Code Playgroud)

接下来安装 pytesseract 库并重新启动运行时。

!pip install pytesseract==0.3.9
Run Code Online (Sandbox Code Playgroud)

确保重新启动运行时,重新启动运行时后,执行代码。在工作区上传图像或从驱动器获取路径并使用它而不是此处声明的路径。

import pytesseract
from pytesseract import Output
from PIL import Image
import cv2
imag = cv2.imread('/content/1.jpg')

d = pytesseract.image_to_data(imag, output_type=Output.DICT)
print(d.keys())
Run Code Online (Sandbox Code Playgroud)

这会对你有所帮助。供参考colab 笔记本

输出看起来像,

dict_keys(['level', 'page_num', 'block_num', 'par_num', 'line_num', 'word_num', 'left', 'top', 'width', 'height', 'conf', 'text'])
Run Code Online (Sandbox Code Playgroud)