python - OCR 文件夹中的每个 .png 文件

标签 python ocr

我想遍历文件夹中的每个 .png 文件并打印图像中包含的每个文本。第一次迭代工作正常,但第二次出现错误。

代码:

import pytesseract
from PIL import Image
import os

directory = (r'C:\folder...')

for filename in os.listdir(directory):
    if filename.endswith('.png'):
        Image = Image.open(filename)
        im = pytesseract.image_to_string(Image)
        print(im)

输出:

Traceback (most recent call last): File "C:\Users\Artur\Desktop\Pytesseract_test.py", line 9, in Image = Image.open(filename) AttributeError: 'PngImageFile' object has no attribute 'open'

“PngImageFile”对象没有属性“open”是什么意思? Image = Image.open(filename) 不正是这样做的吗?

提前致谢

编辑:

最初的 PngError 已解决,但现在发生了 PIL 库的另一个错误:

import pytesseract
from PIL import Image
import os

directory = (r'C:\folder...')

for filename in os.listdir(directory):
    if filename.endswith('.png'):
        img = Image.open(filename)
        im = pytesseract.image_to_string(img)
        print(im)

输出:('frame_0000.png' 的 ocr 正确然后)

Traceback (most recent call last):
  File "C:\Users\Artur\Desktop\Pytesseract_test.py", line 9, in <module>
    img = Image.open(filename)
  File "C:\Users\Artur\AppData\Local\Programs\Python\Python36\lib\site-packages\PIL\Image.py", line 2580, in open
    fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'frame_0001.png'

编辑2:

这很奇怪。当我这样做时:

for filename in os.listdir(r'folderpath...'):
    print(filename)

它工作得非常好,遍历每个文件,打印每个文件名。

但是当我这样做的时候:

for filename in os.listdir(r'folderpath...'):
    print(filename)
    print(pytesseract.image_to_string(Image.open(filename)))

出现错误:

Bewegung_UHF_Plots.m
Traceback (most recent call last):
  File "C:\Users\Artur\Desktop\Pytesseract_test.py", line 19, in <module>
    print(pytesseract.image_to_string(Image.open(filename)))
  File "C:\Users\Artur\AppData\Local\Programs\Python\Python36\lib\site-packages\PIL\Image.py", line 2580, in open
    fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'Bewegung_UHF_Plots.m'

最佳答案

将变量 Image 的名称更改为其他名称,例如 picpicture

关于python - OCR 文件夹中的每个 .png 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51157661/

相关文章:

python - Golang 和 Python 执行 http 请求的方法之间的根本区别?

python - Django-ManyToMany表提取了错误的信息

python - 如何消除文本图像的倾斜并检索该图像的新边界框 Python OpenCV?

Azure Text 检测是手写还是 ocr

python - 属性错误: 'module' object has no attribute 'm1'

ios - iPhone 艾比 OCR

python - 如何从 SQL 查询创建 JSON 文件?

python - Argparse 和几个排他性参数

matlab - 使用反向传播算法进行字符识别测试

python - 什么行为是首选? (嵌入 Python)