Last active
October 15, 2021 13:23
-
-
Save ecmjohnson/43db482b2e3711b96a943a516550c219 to your computer and use it in GitHub Desktop.
Utility for batch modifying images
This file contains 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 sys, os | |
import numpy as np | |
import imageio | |
from absl import app, flags | |
from tqdm import tqdm | |
opts = flags.FLAGS | |
flags.DEFINE_string('input_dir', 'masks', 'Input directory') | |
flags.DEFINE_string('output_dir', 'results', 'Outut directory') | |
to8b = lambda x: (255 * np.clip(x, 0, 1)).astype(np.uint8) | |
def process(img): | |
# e.g. closing for a binary mask | |
from skimage.color import rgb2gray | |
from skimage.morphology import disk, closing | |
return closing(rgb2gray(img), disk(5))[..., None].repeat(3, axis=-1) | |
def rename(in_file): | |
# e.g. re-numbering to a 1-indexed naming | |
number = int(in_file.split('.')[0]) | |
return '{:04d}.png'.format(number + 1) | |
def main(_): | |
os.makedirs(opts.output_dir, exist_ok=True) | |
in_files = [f for f in os.listdir(opts.input_dir) if f.endswith('.png')] | |
for in_file in tqdm(in_files): | |
img = imageio.imread(os.path.join(opts.input_dir, in_file)) | |
img = process(img) | |
imageio.imwrite( | |
os.path.join(opts.output_dir, rename(in_file)), | |
to8b(img) | |
) | |
if __name__ == "__main__": | |
app.run(main) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment