Loading All Images Using Imread from a Given Folder

Python/OpenCV - how to load all images from folder in alphabetical order

Luckily, python lists have a built-in sort function that can sort strings using ASCII values. It is as simple as putting this before your loop:

filenames = [img for img in glob.glob("images/*.jpg")]

filenames.sort() # ADD THIS LINE

images = []
for img in filenames:
n= cv2.imread(img)
images.append(n)
print (img)

EDIT: Knowing a little more about python now than I did when I first answered this, you could actually simplify this a lot:

filenames = glob.glob("images/*.jpg")
filenames.sort()
images = [cv2.imread(img) for img in filenames]

for img in images:
print img

Should be much faster too. Yay list comprehensions!

How to read images from a directory with Python and OpenCV?

You have post at least three questions about get filenames with "PostPath". Badly.

A better way is use glob.glob to get the specific type of filenames.

$ tree .
├── a.txt
├── feature.py
├── img01.jpg
├── img01.png
├── imgs
│   ├── img02.jpg
│   └── img02.png
├── tt01.py
├── tt02.py
└── utils.py

1 directory, 9 files

From current directory:

import glob
import itertools

def getFilenames(exts):
fnames = [glob.glob(ext) for ext in exts]
fnames = list(itertools.chain.from_iterable(fnames))
return fnames


## get `.py` and `.txt` in current folder
exts = ["*.py","*.txt"]
res = getFilenames(exts)
print(res)
# ['utils.py', 'tt02.py', 'feature.py', 'tt01.py', 'a.txt']


# get `.png` in current folder and subfolders
exts = ["*.png","*/*.png"]
res = getFilenames(exts)
print(res)
# ['img01.png', 'imgs/img02.png']

Importing images from a directory (Python) to list or dictionary

I'd start by using glob:

from PIL import Image
import glob
image_list = []
for filename in glob.glob('yourpath/*.gif'): #assuming gif
im=Image.open(filename)
image_list.append(im)

then do what you need to do with your list of images (image_list).



Related Topics



Leave a reply



Submit