Skip to content

Instantly share code, notes, and snippets.

@aplz
Created July 24, 2018 09:45
Show Gist options
  • Save aplz/1869367ea2f8a9bdd6e80abcdf68143b to your computer and use it in GitHub Desktop.
Save aplz/1869367ea2f8a9bdd6e80abcdf68143b to your computer and use it in GitHub Desktop.
def rotateWithShapeFit(image, rotations=None):
"""
Rotates the given image by 90, 180 or 270 degrees, keeping the original image shape.
The original shape is kept by adding black borders both at the top and bottom or the left and the right of the
rotated image.
Args:
image: the image to rotate.
rotations: the number of rotations by 90 degrees. 1 will rotate the image by 90°, 2 by 180° and 3 by 270°.
Returns:
the rotated image.
"""
original_width = image.shape[1]
original_height = image.shape[0]
if rotations is None:
# Choose a random number of rotations between 1 and 3 (the endpoint of randrange is not included).
# We don't need 360° since this would be the original image.
rotations = random.randrange(1, 4, 1)
rotated = np.rot90(image, rotations)
height_addition = 0
width_addition = 0
# Compare the aspect ratio of the input image to that of the rotated image to determine whether borders should be
# added to increase the width or height.
if (original_height / original_width) >= (rotated.shape[0] / rotated.shape[1]):
# Compute the height of an image with the same aspect ratio as the rotated image, but with width equal to the
# input image. Then subtract the actual height of the image to determine how large the borders need to be.
# Finally, divide by two as the border is added at the top and the bottom (or at the left and right in case of
# width_addition).
height_addition = int((((original_height / original_width) * rotated.shape[1]) - rotated.shape[0]) / 2)
else:
width_addition = int((((original_width / original_height) * rotated.shape[0]) - rotated.shape[1]) / 2)
# cv2.copyMakeBorder, this creates an image with the target aspect ratio with black bars "filling in" the
# difference between the aspect ratios.
rotated = cv2.copyMakeBorder(rotated, top=height_addition, bottom=height_addition,
left=width_addition, right=width_addition,
borderType=cv2.BORDER_CONSTANT, value=0)
rotated = cv2.resize(rotated, (original_width, original_height))
return rotated
@aplz
Copy link
Author

aplz commented Jul 24, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment