When the neural network prepares the training set, it is often necessary to read all the pictures from the folder. There are often two ways
1 os.listdir()
os.listdir() is to list all file names in the folder. Then use the os.path.join() function to join the address of the folder with the folder name to obtain the absolute address.
import os
files=os.listdir('./T91_HR')
print(type(files))
print(files)
for i in files:
path=os.path.join('./T91_HR/'+i)
print(path)
2 glob
glob
is a language for matching collections of files that match a specified pattern
Returns a list of all matching file paths. It has only one parameter pathname, which defines the file path matching rules, where it can be an absolute path or a relative path
glob.glob()
What is returned here is a list
from glob import glob
import os
path=os.path.join('./T91_HR/*.png')
files=glob(path)
print(type(files))
for i in files:
print(i)
glob.iglob()
This function is similar to the glob.glob() function, and only has one parameter, pathname, but this function returns an iterator, which means that only one path is returned at a time, which takes up less memory than glob.glob() .
from glob import iglob
import os
path=os.path.join('./T91_HR/*.png')
files=iglob(path)
print(type(files))
natural sort
from natsort import natsorted
a = ['1.png', '3.png', '10.png', '2.png']
##常规排序
a.sort()
print(a)
##自然排序
b = natsorted(a)
print(b)