|
import numpy as np |
|
|
|
def pad_to_center(img,img_height, img_width, req_height, req_width): |
|
""" |
|
Goal of this function is to increase original image size, upto the |
|
req_height and width. |
|
|
|
Parameters: |
|
img -> 3D numpy array of shape Height x Width x Channels |
|
img_height -> height of current image |
|
img_width -> width of current image |
|
req_height -> max height you want your image to be padded to. |
|
req_width -> max width you want your image to be padded to. |
|
""" |
|
|
|
|
|
|
|
rem_height = req_height - img_height |
|
rem_width = req_width - img_width |
|
|
|
|
|
|
|
pad_top = rem_height // 2 |
|
pad_bottom = rem_height - pad_top |
|
|
|
|
|
|
|
pad_left = rem_width // 2 |
|
pad_right = rem_width - pad_left |
|
|
|
|
|
|
|
return np.pad( |
|
img, |
|
( |
|
(pad_top, pad_bottom), |
|
(pad_left, pad_right), |
|
(0,0) |
|
), |
|
|
|
mode = 'reflect' |
|
) |
|
|
|
|
|
def crop_to_center(img, img_height, img_width, req_height, req_width, req_channel = 3): |
|
""" |
|
Goal of this function is to reduce the original image(s) size to the required height and width, |
|
by making sure that we only trim the edges of images and not the middle part. |
|
|
|
Parameters: |
|
img -> 4d numpy array batch_size/num frames x Height x width x Channels |
|
""" |
|
|
|
|
|
toph = (img_height - req_height)//2 |
|
leftw = (img_width - req_width)//2 |
|
|
|
|
|
bothen = img_height - toph |
|
|
|
|
|
rightwen = img_width - leftw |
|
|
|
cropped_image = img[toph:bothen, leftw:rightwen, :] |
|
|
|
assert cropped_image.shape == (req_height, req_width, req_channel) |
|
return cropped_image |
|
|
|
|
|
def preprocess_images(img, req_height, req_width): |
|
|
|
""" |
|
Crops the input image array to the specified height and width, |
|
centered around the middle. |
|
|
|
Args: |
|
img (np.ndarray): The image to crop, represented as a NumPy array |
|
(height, width, channels). |
|
crop_height (int): The desired height of the cropped image. |
|
crop_width (int): The desired width of the cropped image. |
|
|
|
Returns: |
|
np.ndarray: The center-cropped image. |
|
""" |
|
|
|
image_shape_tuple = img.shape |
|
assert len(image_shape_tuple) == 3, f"Please pass a 3D image with height, width and channels , you passed: {image_shape_tuple}" |
|
|
|
|
|
img_height, img_width, img_channel = image_shape_tuple |
|
|
|
|
|
|
|
if img_height < req_height or img_width < req_width: |
|
return pad_to_center(img, img_height, img_width, req_height, req_width) |
|
|
|
|
|
elif img_height == req_height and img_width == req_width: |
|
return img |
|
|
|
|
|
else: |
|
return crop_to_center(img, |
|
img_height, |
|
img_width, |
|
req_height, |
|
req_width, |
|
img_channel |
|
) |