Loading files from a directory is a common use case. This is done by identifying a list of files in a directory, filtering the necessary files, and then executing a set of operations for each and every one of them.
We will be using the sample-images folder from the GitHub repository. You are required to have a functioning project folder when running the following example:
using Images
directory_path = "sample-images";
directory_files = readdir(directory_path);
directory_images = filter(x -> ismatch(r"\.(jpg|png|gif){1}$"i, x), directory_files);
for image_name in directory_images
image_path = joinpath(directory_path, image_name);
image = load(image_path);
# other operations
end
This example introduces a number of new functions and techniques, which are explained as follows:
- We use readdir from the Julia Base to read all the files names in a directory
- We use filter from the Julia Base, as well as custom regular expressions to find files ending with .jpg, .png, or .gif, both in lower and upper-case
- We use the for loop to iterate over filtered names
- We use joinpath from the Julia Base to combine the directory name and filename so that we have a full path to the image
- We use the load function (which you have already learned about) to load the image
Please be aware that readdir returns filenames. This is the reason for us using joinpath, which joins components into a full path.