Skip to content

Commit 67d72ae

Browse files
committed
Make center_crop_and_resize support non-quadratics
Make the function center_crop_and_resize() support non-quadratic output shapes and crop padding shapes. The arguments image_size and crop_padding should be able to either be scalars (like they currently are) or lists or tuples containing both a height and a width.
1 parent 8aa3fa5 commit 67d72ae

File tree

1 file changed

+26
-9
lines changed

1 file changed

+26
-9
lines changed

efficientnet/preprocessing.py

+26-9
Original file line numberDiff line numberDiff line change
@@ -30,21 +30,38 @@ def center_crop_and_resize(image, image_size, crop_padding=32, interpolation="bi
3030
assert image.ndim in {2, 3}
3131
assert interpolation in MAP_INTERPOLATION_TO_ORDER.keys()
3232

33-
h, w = image.shape[:2]
33+
in_h, in_w = image.shape[:2]
3434

35-
padded_center_crop_size = int(
36-
(image_size / (image_size + crop_padding)) * min(h, w)
37-
)
38-
offset_height = ((h - padded_center_crop_size) + 1) // 2
39-
offset_width = ((w - padded_center_crop_size) + 1) // 2
35+
if isinstance(image_size, (int, float)):
36+
out_h = out_w = image_size
37+
else:
38+
out_h, out_w = image_size
39+
40+
if isinstance(crop_padding, (int, float)):
41+
crop_padding_h = crop_padding_w = crop_padding
42+
else:
43+
crop_padding_h, crop_padding_w = crop_padding
44+
45+
padded_center_crop_shape_post_scaling = (out_h + crop_padding_h,
46+
out_w + crop_padding_w)
47+
48+
scale = min(in_h / padded_center_crop_shape_post_scaling[0],
49+
in_w / padded_center_crop_shape_post_scaling[1])
50+
51+
unpadded_center_crop_size_pre_scaling = (round(out_h * scale),
52+
round(out_w * scale))
53+
54+
offset_h = ((in_h - unpadded_center_crop_size_pre_scaling[0]) + 1) // 2
55+
offset_w = ((in_w - unpadded_center_crop_size_pre_scaling[1]) + 1) // 2
4056

4157
image_crop = image[
42-
offset_height : padded_center_crop_size + offset_height,
43-
offset_width : padded_center_crop_size + offset_width,
58+
offset_h : unpadded_center_crop_size_pre_scaling[0] + offset_h,
59+
offset_w : unpadded_center_crop_size_pre_scaling[1] + offset_w,
4460
]
61+
4562
resized_image = resize(
4663
image_crop,
47-
(image_size, image_size),
64+
(out_h, out_w),
4865
order=MAP_INTERPOLATION_TO_ORDER[interpolation],
4966
preserve_range=True,
5067
)

0 commit comments

Comments
 (0)