| 1 | import numpy as np |
| 2 | |
| 3 | from .resize import resize |
| 4 | |
| 5 | |
| 6 | def centerize( |
| 7 | src, |
| 8 | shape, |
| 9 | cval=None, |
| 10 | return_mask=False, |
| 11 | interpolation="linear", |
| 12 | loc="center", |
| 13 | ): |
| 14 | """Centerize image for specified image size |
| 15 | |
| 16 | Parameters |
| 17 | ---------- |
| 18 | src: numpy.ndarray |
| 19 | Image to centerize |
| 20 | shape: tuple of int |
| 21 | Image shape (height, width) or (height, width, channel) |
| 22 | cval: int or float or numpy.ndarray |
| 23 | Color to be filled in the blank. |
| 24 | return_mask: numpy.ndarray |
| 25 | Mask for centerized image. |
| 26 | interpolation: str |
| 27 | Interpolation method (default: 'linear'). |
| 28 | loc: str |
| 29 | Location of image ('center', 'lt', 'rb'). (default: 'center') |
| 30 | |
| 31 | Returns |
| 32 | ------- |
| 33 | dst: numpy.ndarray |
| 34 | Centerized image. |
| 35 | |
| 36 | """ |
| 37 | if src.shape[:2] == shape[:2]: |
| 38 | if return_mask: |
| 39 | return src, np.ones(shape[:2], dtype=bool) |
| 40 | else: |
| 41 | return src |
| 42 | |
| 43 | if len(shape) != src.ndim: |
| 44 | shape = list(shape) + [src.shape[2]] |
| 45 | |
| 46 | dst = np.zeros(shape, dtype=src.dtype) |
| 47 | if cval: |
| 48 | dst[:, :] = cval |
| 49 | |
| 50 | src_h, src_w = src.shape[:2] |
| 51 | scale_h, scale_w = 1.0 * shape[0] / src_h, 1.0 * shape[1] / src_w |
| 52 | scale = min(scale_h, scale_w) |
| 53 | dst_h, dst_w = int(round(src_h * scale)), int(round(src_w * scale)) |
| 54 | src = resize(src, height=dst_h, width=dst_w, interpolation=interpolation) |
| 55 | |
| 56 | ph, pw = 0, 0 |
| 57 | h, w = src.shape[:2] |
| 58 | dst_h, dst_w = shape[:2] |
| 59 | if loc == "center": |
| 60 | if h < dst_h: |
| 61 | ph = (dst_h - h) // 2 |
| 62 | if w < dst_w: |
| 63 | pw = (dst_w - w) // 2 |
| 64 | elif loc == "lt": |
| 65 | ph = 0 |
| 66 | pw = 0 |
| 67 | elif loc == "rb": |
| 68 | if h < dst_h: |
| 69 | ph = dst_h - h |
| 70 | if w < dst_w: |
| 71 | pw = dst_w - w |
| 72 | else: |
| 73 | raise ValueError("Unsupported loc: {}".format(loc)) |
| 74 | dst[ph : ph + h, pw : pw + w] = src |
| 75 | |
| 76 | if return_mask: |
| 77 | mask = np.zeros(shape[:2], dtype=bool) |
| 78 | mask[ph : ph + h, pw : pw + w] = True |
| 79 | return dst, mask |
| 80 | else: |
| 81 | return dst |