Skip to content

Commit 356f107

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 d740fc8 commit 356f107

File tree

1 file changed

+25
-9
lines changed

1 file changed

+25
-9
lines changed

efficientnet/preprocessing.py

+25-9
Original file line numberDiff line numberDiff line change
@@ -27,21 +27,37 @@ def center_crop_and_resize(image, image_size, crop_padding=32, interpolation="bi
2727
assert image.ndim in {2, 3}
2828
assert interpolation in MAP_INTERPOLATION_TO_ORDER.keys()
2929

30-
h, w = image.shape[:2]
30+
in_h, in_w = image.shape[:2]
3131

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

3854
image_crop = image[
39-
offset_height: padded_center_crop_size + offset_height,
40-
offset_width: padded_center_crop_size + offset_width,
55+
offset_h : unpadded_center_crop_size_pre_scaling[0] + offset_h,
56+
offset_w : unpadded_center_crop_size_pre_scaling[1] + offset_w,
4157
]
4258
resized_image = resize(
4359
image_crop,
44-
(image_size, image_size),
60+
(out_h, out_w),
4561
order=MAP_INTERPOLATION_TO_ORDER[interpolation],
4662
preserve_range=True,
4763
)

0 commit comments

Comments
 (0)