Iterate through folder with Pillow Image.open

2019-08-02 03:33发布

问题:

I am trying to iterate through a folder of .png files and OCR them. The iteration works but as soon as I try to open Images with PIL it gives errors.

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)

This works just fine. It prints every .png filename in the folder. But when I try to 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)))

Output:

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'

Edit:

Thanks to Benehiko it works fine now.

Code:

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))

回答1:

I have a python script opening jpg images from a folder using glob. Opening png will be the same concept by just changing the ".jpg" to ".png"

Iterate through a folder

The Code I use in my case is as follows:

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()