| 17 | |
| 18 | |
| 19 | def generate_mask(trans_image, im_shape, resolution, polygon, location): |
| 20 | if isinstance(im_shape, int): im_shape = (im_shape, im_shape) |
| 21 | mask = Image.new("L", im_shape, 255) |
| 22 | draw = ImageDraw.Draw(mask) |
| 23 | polygon_int = [(int(x), int(y)) for x, y in polygon] |
| 24 | draw.polygon(polygon_int, fill=0) |
| 25 | mask = np.array(mask.convert("L"))[location[1]:location[3], location[0]:location[2]] |
| 26 | transform = transforms.Compose([ |
| 27 | transforms.ToTensor(), |
| 28 | transforms.Resize((resolution, resolution)) |
| 29 | ]) |
| 30 | mask = transform(mask) |
| 31 | mask = torch.where(mask < 0.5, torch.tensor(0.0), torch.tensor(1.0)) |
| 32 | masked_image = trans_image * mask.expand_as(trans_image) |
| 33 | |
| 34 | mask_np = mask.squeeze().byte().cpu().numpy() |
| 35 | mask_np = np.transpose(mask_np) |
| 36 | points = np.column_stack(np.where(mask_np == 0)) |
| 37 | rect = cv2.minAreaRect(points) |
| 38 | |
| 39 | return mask, masked_image, rect |
| 40 | |
| 41 | |
| 42 | def calculate_square(full_image, polygon): |