Skip to content

Instantly share code, notes, and snippets.

@universvm
Last active November 17, 2020 11:29
Show Gist options
  • Save universvm/68691582ca1a385105f82e69d49c8784 to your computer and use it in GitHub Desktop.
Save universvm/68691582ca1a385105f82e69d49c8784 to your computer and use it in GitHub Desktop.
[Resize all imgs in a directory] #Python
import os
import pandas as pd
from cv2 import imread, resize, imwrite, IMREAD_GRAYSCALE, INTER_AREA
# Extension of files needed:
ext = '.jpg'
label_ext = '.txt'
# Directory of interest:
dir_path = 'dataset'
out_path = 'resized_dataset'
resize_factor = 2
LABEL_SEPARATOR = '\n'
# Loop through files:
for (dirpath, dirnames, filenames) in os.walk(dir_path):
# Loop through Annotations:
for i in range(len(filenames)):
# Open files of interest:
if filenames[i].endswith(ext):
img_path = os.path.join(dirpath, filenames[i])
current_img = imread(img_path, IMREAD_GRAYSCALE)
label_df = pd.read_csv(os.path.join(img_path.split(ext)[0] +
label_ext),
sep=LABEL_SEPARATOR, header=None)
# Resize:
print(int(current_img.shape[0]/resize_factor))
resized_img = resize(current_img, (int(current_img.shape[0]/resize_factor),
int(current_img.shape[1]/resize_factor)),
interpolation=INTER_AREA)
label_df = label_df / resize_factor
# Save:
imwrite(os.path.join(out_path, 'resized' + filenames[i]), resized_img)
label_df.to_csv(os.path.join(out_path, 'resized' +
filenames[i].split(ext)[0] + label_ext),
header=None, index=None, sep=LABEL_SEPARATOR,
encoding='utf-8')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment