Skip to content

Instantly share code, notes, and snippets.

@amir-saniyan
Last active October 17, 2024 03:59
Show Gist options
  • Save amir-saniyan/3713fd4eb200f10b3d6a11a9dba4ea6d to your computer and use it in GitHub Desktop.
Save amir-saniyan/3713fd4eb200f10b3d6a11a9dba4ea6d to your computer and use it in GitHub Desktop.
Image Cropper
class ImageCropper:
@staticmethod
def crop(image, x, y, width, height):
try:
image_width = image.shape[1]
image_height = image.shape[0]
x = max(0, min(image_width - 1, x))
y = max(0, min(image_height - 1, y))
width = max(0, min(image_width, width))
height = max(0, min(image_height, height))
if x + width > image_width:
width -= (x + width) - image_width + 1
if y + height > image_height:
height -= (y + height) - image_height + 1
if width <= 0 or height <= 0:
return None, None
cropped_image = image[y : y + height, x : x + width]
cropped_area = {
"x": x,
"y": y,
"width": width,
"height": height,
}
return cropped_image, cropped_area
except:
return None
@staticmethod
def square_crop(image, x, y, width, height, grow=0):
try:
image_width = image.shape[1]
image_height = image.shape[0]
x = max(0, min(image_width - 1, x))
y = max(0, min(image_height - 1, y))
width = max(0, min(image_width, width))
height = max(0, min(image_height, height))
if x + width > image_width:
width -= (x + width) - image_width + 1
if y + height > image_height:
height -= (y + height) - image_height + 1
if width <= 0 or height <= 0:
return None
center_x = x + width / 2
center_y = y + height / 2
side = max(width, height)
side += side * grow
new_width = int(side)
new_x = int(center_x - new_width / 2)
new_height = int(side)
new_y = int(center_y - new_height / 2)
return ImageCropper.crop(image, new_x, new_y, new_width, new_height)
except:
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment