Created
March 1, 2019 16:33
-
-
Save bcjarrett/eac5706199ddb645fbdf6a0d63a48f27 to your computer and use it in GitHub Desktop.
Recursively consolidates .TIF and .JPG images into a single directory with file names based on folder names
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import glob | |
import os | |
import pathlib | |
import ntpath | |
import shutil | |
if __name__ == '__main__': | |
def get_image_files(_dir): | |
tif = glob.glob(f'{_dir}/**/*.tif', recursive=True) | |
jpg = glob.glob(f'{_dir}/**/*.jpg', recursive=True) | |
return tif + jpg | |
def parent_folder_names(base_folder, _file): | |
_file_split = _file.split('\\') | |
_folder_split = base_folder.split('\\') | |
return _file_split[len(_folder_split): len(_file_split) - 1] | |
working_dir = os.path.dirname(os.path.realpath(__file__)) | |
new_folder_of_images = 'consolidated_images' | |
# Generate unique list of images in the image dir and all the subdirectories | |
images = get_image_files(working_dir) | |
con_folder = f'{working_dir}\\{new_folder_of_images}' | |
pathlib.Path(f'{con_folder}').mkdir(parents=True, exist_ok=True) | |
# Rename images with our folder naming convention | |
for image in images: | |
_ = '_'.join(parent_folder_names(working_dir, image)) | |
img_name = _ + '_' + ntpath.basename(image) if _ else ntpath.basename(image) | |
print(f'{image} -> {con_folder}\\{img_name}') | |
shutil.copyfile(image, f'{con_folder}\\{img_name}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment