gpt4 book ai didi

python - 使用 Pillow Image.open 遍历文件夹

转载 作者:行者123 更新时间:2023-12-01 01:47:10 25 4
gpt4 key购买 nike

我正在尝试遍历 .png 文件的文件夹并对它们进行 OCR。迭代有效,但是当我尝试使用 PIL 打开图像时,它就会出现错误。

import pytesseract
from PIL import Image
import os

for filename in os.listdir('C:/Users/Artur/Desktop/Sequenz_1'):
if filename.endswith('.png'):
print(filename)

这工作得很好。它打印文件夹中的每个 .png 文件名。但是当我尝试 OCR 时:

import pytesseract
from PIL import Image
import os

for filename in os.listdir('C:/Users/Artur/Desktop/Sequenz_1'):
if filename.endswith('.png'):
print(pytesseract.image_to_string(Image.open(filename)))

输出:

Traceback (most recent call last):
File "C:\Users\Artur\Desktop\Pytesseract_test.py", line 8, 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: 'frame_0000.png'

编辑:

感谢 Benehiko,现在一切正常。

代码:

import pytesseract
from PIL import Image
import glob


images = glob.glob('C:/Users/Artur/Desktop/Sequenz_1/*.png')

for image in images:
with open(image, 'rb') as file:
img = Image.open(file)
print(pytesseract.image_to_string(img))

最佳答案

我有一个 python 脚本,使用 glob 从文件夹中打开 jpg 图像。打开 png 将是相同的概念,只需将“.jpg”更改为“.png”

Iterate through a folder

我在我的案例中使用的代码如下:

import glob
from PIL import Image

images = glob.glob("Images/*.jpg")
for image in images:
with open(image, 'rb') as file:
img = Image.open(file)
img.show()

关于python - 使用 Pillow Image.open 遍历文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51178166/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com