Created
August 6, 2024 10:29
-
-
Save optinsoft/e5a03fe4d0c4087d41c3e536f75c476d to your computer and use it in GitHub Desktop.
Resize OpenCV image (crop or add border when required)
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 | |
| RESIZE_IMAGE_CROP: int = 0 | |
| RESIZE_IMAGE_PAD: int = 1 | |
| ResizeImageFlags = int | |
| """One of [RESIZE_IMAGE_CROP(default), RESIZE_IMAGE_PAD]""" | |
| def resize_image_canvas(img: cv2.typing.MatLike, new_image_width: int, new_image_height: int, flags: ResizeImageFlags) -> cv2.typing.MatLike: | |
| old_image_height, old_image_width = img.shape[:2] | |
| if flags == RESIZE_IMAGE_PAD: | |
| w = max(new_image_width, old_image_width) | |
| h = max(new_image_height, old_image_height) | |
| crop_width = old_image_width | |
| crop_height = old_image_height | |
| cropped_image = img | |
| else: | |
| w = new_image_width | |
| h = new_image_height | |
| crop_width = min(w, old_image_width) | |
| crop_height = min(h, old_image_height) | |
| cropped_image = img[0:crop_height, 0:crop_width] | |
| left = (w - crop_width) // 2 | |
| top = (h - crop_height) // 2 | |
| right = w - left - crop_width | |
| bottom = h - top - crop_height | |
| return cv2.copyMakeBorder(cropped_image, top, bottom, left, right, cv2.BORDER_CONSTANT) | |
| def imshowsize(winname: str, img: cv2.typing.MatLike, new_image_width: int = 0, new_image_height: int = 0): | |
| new_img = resize_image_canvas(img, new_image_width, new_image_height, RESIZE_IMAGE_PAD) | |
| cv2.imshow(winname, new_img) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment