Created
February 26, 2022 11:26
-
-
Save ovuruska/d872512c263b627a7e6ecd856188a17b to your computer and use it in GitHub Desktop.
Get images from subdirectories
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 argparse | |
| from shutil import rmtree | |
| import cv2 | |
| import os | |
| import pathlib | |
| from tqdm import tqdm | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--images-dir","-I",default="images",help="Directory of input images") | |
| parser.add_argument("--out-dir","-O",default="out",help="Directory of extracted images") | |
| parser.add_argument("--start-index","-S",default=1,help="Starting index for image naming") | |
| if __name__ == "__main__": | |
| args = parser.parse_args() | |
| images_dir = args.images_dir | |
| out_dir = args.out_dir | |
| index = int(args.start_index) | |
| if os.path.exists(out_dir): | |
| rmtree(out_dir) | |
| pathlib.Path(out_dir).mkdir(parents=True, exist_ok=True) | |
| pbar = tqdm(os.walk(images_dir),desc="Number of images",unit=" images") | |
| for root, subdirectories, files in pbar: | |
| for file in files: | |
| try: | |
| pbar.update() | |
| image = cv2.imread(os.path.join(root,file)) | |
| if image is None: | |
| continue | |
| else: | |
| out_path = os.path.join(out_dir,f"{index}.png") | |
| cv2.imwrite(out_path,image) | |
| index += 1 | |
| pbar.update() | |
| except cv2.error: | |
| continue |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment