So, the scheme is that I have a folder, inside which there are other folders with .tif images. For instance I have something like that:
folder_1/folder_2/folder_3/image_1.tif
folder_1/folder_2/image_2.tif
folder_1/image_3.tif
folder_1/folder_2/folder_3/image_4.tif
I need to read all the .tif images from all folders. I tried this suggestion: Loading all images using imread from a given folder but it does not work for variable path folders, as my scheme. So, after searching I tried this suggestion: Loading multiple images from multiple folders in python but I get this error:
raise UnidentifiedImageError(
PIL.UnidentifiedImageError: cannot identify image file(....)
Any idea how to read all .tif images from all folders, which vary in "folder distance" from the initial folder?
>Solution :
The glob module helps with this.
from glob import glob
import os.path
parent_dir = "C:\\folder_1" # Or wherever your parent folder is
all_tif_file_paths = glob(os.path.join(parent_dir, "**", "*.tif"), recursive=True)
The "**" there means ‘any number (including zero) of intervening directories’, and when you use it, you need to specify recursive=True.
Then you can loop over all_tif_file_paths and read each file in turn.