Skip to content

Instantly share code, notes, and snippets.

@i-namekawa
Last active April 10, 2024 22:56
Show Gist options
  • Save i-namekawa/74a817683b0e68cee521 to your computer and use it in GitHub Desktop.
Save i-namekawa/74a817683b0e68cee521 to your computer and use it in GitHub Desktop.
zoom in/out an image (numpy array) while keeping the original shape.
import cv2
def paddedzoom(img, zoomfactor=0.8):
'''
Zoom in/out an image while keeping the input image shape.
i.e., zero pad when factor<1, clip out when factor>1.
there is another version below (paddedzoom2)
'''
out = np.zeros_like(img)
zoomed = cv2.resize(img, None, fx=zoomfactor, fy=zoomfactor)
h, w = img.shape
zh, zw = zoomed.shape
if zoomfactor<1: # zero padded
out[(h-zh)/2:-(h-zh)/2, (w-zw)/2:-(w-zw)/2] = zoomed
else: # clip out
out = zoomed[(zh-h)/2:-(zh-h)/2, (zw-w)/2:-(zw-w)/2]
return out
def paddedzoom2(img, zoomfactor=0.8):
' does the same thing as paddedzoom '
h,w = img.shape
M = cv2.getRotationMatrix2D( (w/2,h/2), 0, zoomfactor)
return cv2.warpAffine(img, M, img.shape[::-1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment