我想迭代文件夹中的每个.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)
输出:
回溯(最近一次调用最后一次):文件“C:\ Users \ Artur \ Desktop \ Pytesseract_test.py”,第9行,在Image = Image.open(filename)中AttributeError:'PngImageFile'对象没有属性'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'
EDIT2:
这很奇怪 . 当我这样做:
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'
2 回答
将变量
Image
的名称更改为pic
或picture
之类的其他名称您的第一个传递创建一个对象
Image
,它是Image.open(filename)
,或者'Image'类的'open'方法实现文件'filename' . 这是您在每次迭代时想要的 . 不幸的是,你在Image.open(filename)
中的图像' class out in favor of your new '图像'并不是指'Image'类,而是指你的'Image'对象 .通过更改来解决您的问题:
至: