r""" Finds a rectangular region that contains all masked ares in an image, and expands region to match the aspect ratio of the original image; for example, if user drew mask in a 128x32 region, and the dimensions for processing are 512x512, the region will be expanded to 128x
(mask_image: PIL.Image.Image, width: int, height: int, pad=0)
| 286 | |
| 287 | @staticmethod |
| 288 | def get_crop_region(mask_image: PIL.Image.Image, width: int, height: int, pad=0): |
| 289 | r""" |
| 290 | Finds a rectangular region that contains all masked ares in an image, and expands region to match the aspect |
| 291 | ratio of the original image; for example, if user drew mask in a 128x32 region, and the dimensions for |
| 292 | processing are 512x512, the region will be expanded to 128x128. |
| 293 | |
| 294 | Args: |
| 295 | mask_image (PIL.Image.Image): Mask image. |
| 296 | width (int): Width of the image to be processed. |
| 297 | height (int): Height of the image to be processed. |
| 298 | pad (int, optional): Padding to be added to the crop region. Defaults to 0. |
| 299 | |
| 300 | Returns: |
| 301 | tuple: (x1, y1, x2, y2) represent a rectangular region that contains all masked ares in an image and |
| 302 | matches the original aspect ratio. |
| 303 | """ |
| 304 | |
| 305 | mask_image = mask_image.convert("L") |
| 306 | mask = np.array(mask_image) |
| 307 | |
| 308 | # 1. find a rectangular region that contains all masked ares in an image |
| 309 | h, w = mask.shape |
| 310 | crop_left = 0 |
| 311 | for i in range(w): |
| 312 | if not (mask[:, i] == 0).all(): |
| 313 | break |
| 314 | crop_left += 1 |
| 315 | |
| 316 | crop_right = 0 |
| 317 | for i in reversed(range(w)): |
| 318 | if not (mask[:, i] == 0).all(): |
| 319 | break |
| 320 | crop_right += 1 |
| 321 | |
| 322 | crop_top = 0 |
| 323 | for i in range(h): |
| 324 | if not (mask[i] == 0).all(): |
| 325 | break |
| 326 | crop_top += 1 |
| 327 | |
| 328 | crop_bottom = 0 |
| 329 | for i in reversed(range(h)): |
| 330 | if not (mask[i] == 0).all(): |
| 331 | break |
| 332 | crop_bottom += 1 |
| 333 | |
| 334 | # 2. add padding to the crop region |
| 335 | x1, y1, x2, y2 = ( |
| 336 | int(max(crop_left - pad, 0)), |
| 337 | int(max(crop_top - pad, 0)), |
| 338 | int(min(w - crop_right + pad, w)), |
| 339 | int(min(h - crop_bottom + pad, h)), |
| 340 | ) |
| 341 | |
| 342 | # 3. expands crop region to match the aspect ratio of the image to be processed |
| 343 | ratio_crop_region = (x2 - x1) / (y2 - y1) |
| 344 | ratio_processing = width / height |
| 345 |
no outgoing calls
no test coverage detected