Skip to content

Instantly share code, notes, and snippets.

@338rajesh
Created August 28, 2023 17:58
Show Gist options
  • Save 338rajesh/9fd4ffad2fe211f69c42f8a7cea36c02 to your computer and use it in GitHub Desktop.
Save 338rajesh/9fd4ffad2fe211f69c42f8a7cea36c02 to your computer and use it in GitHub Desktop.
A simple python script for making a .npy file of images, given the directory of the images.
"""
It prepares and saves .npy array to the specified path.
"""
import os
import numpy as np
import sys
from PIL import Image
from tqdm import tqdm
import argparse
parser = argparse.ArgumentParser(description="Saving images as a numpy .npy file")
parser.add_argument("images_dir", type=str)
parser.add_argument("output_path", type=str)
parser.add_argument("-n", "--number_of_pixels", type=int)
parser.add_argument("-v", "--verbose", action="store_true")
parser.add_argument("-z", "--save_compressed", action="store_true")
parser.add_argument("-c", "--add_channel_dim", action="store_true")
args = parser.parse_args()
#
assert os.path.isdir(args.images_dir), "The images directory is invalid."
images = []
for i in tqdm(os.listdir(args.images_dir), ascii=True):
if i.split(".")[-1] == "png":
images.append(np.array(
Image.open(os.path.join(args.images_dir, i)).resize(
(args.number_of_pixels, args.number_of_pixels)
), dtype=np.uint8
))
images = np.stack(images, axis=0)
if args.add_channel_dim:
images = np.expand_dims(images, axis=1)
if args.verbose:
print(f"An array with {images.shape} is preapred and being saved at {args.output_path}.")
if args.save_compressed:
assert args.output_path.split(".")[-1].lower() == "npz", (
"For saving file in compressed format, output path must have npz extension"
)
np.savez_compressed(args.output_path, images)
else:
np.save(args.output_path, images)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment