Created
December 27, 2018 17:46
-
-
Save ManuelZ/ed83af21814147a659f8b53acf5988e8 to your computer and use it in GitHub Desktop.
Resize images with a width or height larger than certain number of pixels
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
""" | |
Resize images with a width or height larger than MAX_SIZE pixels. | |
BEWARE, it will OVERWRITE images. | |
Is meant to be used with Python 3. | |
Call it with: | |
python resize_images.py --dataset dataset | |
""" | |
from imutils import paths | |
import argparse | |
import cv2 | |
import os | |
import re | |
MAX_SIZE = 900 # pixels | |
def read_im(path_to_file): | |
""" Read a color image from a file. """ | |
return cv2.imread(path_to_file, cv2.IMREAD_COLOR) | |
def resize(im, ratio=0.5): | |
""" Resize an image to attain a target ratio """ | |
(h, w) = im.shape[:2] | |
newDim = (int(w * ratio), int(h * ratio)) | |
return cv2.resize(im, newDim, interpolation = cv2.INTER_AREA) | |
def save_im(im, path_to_file): | |
""" Save an image to disk """ | |
cv2.imwrite(path_to_file, im) | |
ap = argparse.ArgumentParser() | |
ap.add_argument("-i", "--dataset", required=True, help="path to input directory of faces + images") | |
args = vars(ap.parse_args()) | |
imagePaths = list(paths.list_images(args["dataset"])) | |
# loop over the image paths | |
for (i, imagePath) in enumerate(imagePaths): | |
im = read_im(imagePath) | |
(h, w) = im.shape[:2] | |
print("Image '{}' has a size of {}(w) x {}(h)".format(imagePath, w, h)) | |
if ((w > MAX_SIZE) or (h > MAX_SIZE)): | |
im_resized = resize(im, ratio=0.5) | |
(new_h, new_w) = im_resized.shape[:2] | |
# capture the folder path, image name and extension with a regular exp | |
m = re.search('(.*)(\d{8})\.(\w+)', imagePath) | |
if m: | |
folder = m.group(1) | |
imageName = m.group(2) | |
extension = m.group(3) | |
#newImageName = "resized-{}.{}".format(imageName, extension) | |
newImageName = "{}.{}".format(imageName, extension) #will overwrite the file! | |
newFullPath = os.path.join(folder, newImageName) | |
save_im(im_resized, newFullPath) | |
print("New image has a size of {}(w) x {}(h)".format(new_w, new_h)) | |
else: | |
print("Couldn't find the pattern in this image path:\n'{}'".format(imagePath)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment