Created
September 14, 2018 07:11
-
-
Save shenoy-anurag/fb571e083380ce9274537be0956d8a18 to your computer and use it in GitHub Desktop.
This script will resize to an intermediate size and pad an image to desired square size while keeping its aspect ratio unchanged.
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 cv2 | |
import numpy as np | |
def intermediate_scaling(img, intermediate_size): | |
(rows, cols) = img.shape | |
image_size = max(rows, cols) | |
# Rescale to intermediate_size pixels so that image size resembles average size of dataset item. | |
# For example a sample character is resized to average size of dataset | |
scaling_factor = intermediate_size / image_size | |
rows = int(scaling_factor * rows) | |
cols = int(scaling_factor * cols) | |
img = cv2.resize(img, (cols, rows), interpolation=cv2.INTER_CUBIC) | |
return img | |
# Set your desired size and intermediate sizes | |
desired_size = 512 | |
intermediate_size = 400 | |
# Change the image path to a valid one before running | |
im_pth = "image.jpg" | |
im = cv2.imread(im_pth) | |
im = intermediate_scaling(im, intermediate_size) | |
(rows, cols) = im.shape[:2] # shape of im is in (height, width) format | |
# Padding | |
top = bottom = int((desired_size - rows)/2) | |
left = right = int((desired_size - cols)/2) | |
# color = [0, 0, 0] for black and color = [255, 255, 255] for white | |
color = [0, 0, 0] | |
new_im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, | |
value=color) | |
cv2.imwrite('resized.jpg', new_im) | |
cv2.imshow("resized", new_im) | |
cv2.waitKey(0) | |
cv2.destroyAllWindows() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment