Spaces:
Running
on
Zero
Running
on
Zero
import numpy as np | |
def imcrop_center(img_list, crop_p_h, crop_p_w): | |
new_img = [] | |
for i, _img in enumerate(img_list): | |
if crop_p_h / crop_p_w > _img.shape[0] / _img.shape[1]: # crop left and right | |
start_h = int(0) | |
start_w = int((_img.shape[1] - _img.shape[0] / crop_p_h * crop_p_w) / 2) | |
crop_size = (_img.shape[0], int(_img.shape[0] / crop_p_h * crop_p_w)) | |
else: | |
start_h = int((_img.shape[0] - _img.shape[1] / crop_p_w * crop_p_h) / 2) | |
start_w = int(0) | |
crop_size = (int(_img.shape[1] / crop_p_w * crop_p_h), _img.shape[1]) | |
_img_src = crop(_img, start_h, start_w, crop_size[0], crop_size[1]) | |
new_img.append(_img_src) | |
return new_img | |
def crop(img, start_h, start_w, crop_h, crop_w): | |
img_src = np.zeros((crop_h, crop_w, *img.shape[2:]), dtype=img.dtype) | |
hsize, wsize = crop_h, crop_w | |
dh, dw, sh, sw = start_h, start_w, 0, 0 | |
if dh < 0: | |
sh = -dh | |
hsize += dh | |
dh = 0 | |
if dh + hsize > img.shape[0]: | |
hsize = img.shape[0] - dh | |
if dw < 0: | |
sw = -dw | |
wsize += dw | |
dw = 0 | |
if dw + wsize > img.shape[1]: | |
wsize = img.shape[1] - dw | |
img_src[sh : sh + hsize, sw : sw + wsize] = img[dh : dh + hsize, dw : dw + wsize] | |
return img_src | |