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
How to Get Max() to Return Variable Names Instead of Values in Python
Format/Suppress Scientific Notation from Pandas Aggregation Results
Collect_List by Preserving Order Based on Another Variable
Python Flask Threaded True Not Working
How to Use and Print the Pandas Dataframe Name
Get First Date and Last Date of Current Quarter in Python
Compare Two Lists and Find the Unique Values
How to Automatically Download Files from a Pop Up Dialog Using Selenium-Python
Pandas: Merging Two Columns into One With Corresponding Values
Render_Template in Python-Flask Is Not Working
Missing 1 Required Positional Argument - Issue
Most Efficient Way to Forward-Fill Nan Values in Numpy Array
Python - Remove Any Element from a List of Strings That Is a Substring of Another Element
Extract File Name from Read_Csv - Python
Finding Length of the Longest List in an Irregular List of Lists