Skip to content

Instantly share code, notes, and snippets.

@NicholasBallard
Last active August 22, 2021 11:22
Show Gist options
  • Save NicholasBallard/b454eb6cd2e6f66a0346154a435b420b to your computer and use it in GitHub Desktop.
Save NicholasBallard/b454eb6cd2e6f66a0346154a435b420b to your computer and use it in GitHub Desktop.
opencv_resize.py
import cv2
def resize(fp: str, scale: Union[float, int]) -> np.ndarray:
""" Resize an image maintaining its proportions
Args:
fp (str): Path argument to image file
scale (Union[float, int]): Percent as whole number of original image. eg. 53
Returns:
image (np.ndarray): Scaled image
"""
_scale = lambda dim, s: int(dim * s / 100)
im: np.ndarray = cv2.imread(fp)
height, width, channels = im.shape
new_width: int = _scale(width, scale)
new_height: int = _scale(height, scale)
new_dim: tuple = (new_width, new_height)
return cv2.resize(src=im, dsize=new_dim, interpolation=cv2.INTER_LINEAR)
@rkosti
Copy link

rkosti commented Aug 18, 2021

#18 should be:
new_dim: tuple = (new_height, new_width)

@NicholasBallard
Copy link
Author

@rkosti Thank you for looking at the code!
It does appear the dsize in OpenCV is (width, height).
https://docs.opencv.org/master/da/d54/group__imgproc__transform.html#ga47a974309e9102f5f08231edc7e7529d

@rkosti
Copy link

rkosti commented Aug 20, 2021

The dsize in OpenCV is correct.
Your interpretation of the cv2.imread is not. I wrongly pointed to the incorrect part last time. I think it's #15 that needs change.
#15 height, width, channels = im.shape
I hope this helps :)
Screenshot from 2021-08-20 13-19-21

@NicholasBallard
Copy link
Author

@rkosti Thanks for your help fixing the code. Good eagle eyes spotting the transposition.

@rkosti
Copy link

rkosti commented Aug 22, 2021

You're welcome. I realized that my screenshot didn't upload last time. I updated the comment.
Happy Coding :)

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