Get parameters for ``crop`` for a random sized crop. Args: img (PIL Image): Image to be cropped. scale (tuple): range of size of the origin size cropped ratio (tuple): range of aspect ratio of the origin aspect ratio cropped Returns:
(img, scale, ratio)
| 88 | |
| 89 | @staticmethod |
| 90 | def get_params(img, scale, ratio): |
| 91 | """Get parameters for ``crop`` for a random sized crop. |
| 92 | |
| 93 | Args: |
| 94 | img (PIL Image): Image to be cropped. |
| 95 | scale (tuple): range of size of the origin size cropped |
| 96 | ratio (tuple): range of aspect ratio of the origin aspect ratio cropped |
| 97 | |
| 98 | Returns: |
| 99 | tuple: params (i, j, h, w) to be passed to ``crop`` for a random |
| 100 | sized crop. |
| 101 | """ |
| 102 | area = img.size[0] * img.size[1] |
| 103 | |
| 104 | for attempt in range(10): |
| 105 | target_area = random.uniform(*scale) * area |
| 106 | log_ratio = (math.log(ratio[0]), math.log(ratio[1])) |
| 107 | aspect_ratio = math.exp(random.uniform(*log_ratio)) |
| 108 | |
| 109 | w = int(round(math.sqrt(target_area * aspect_ratio))) |
| 110 | h = int(round(math.sqrt(target_area / aspect_ratio))) |
| 111 | |
| 112 | if w <= img.size[0] and h <= img.size[1]: |
| 113 | i = random.randint(0, img.size[1] - h) |
| 114 | j = random.randint(0, img.size[0] - w) |
| 115 | return i, j, h, w |
| 116 | |
| 117 | # Fallback to central crop |
| 118 | in_ratio = img.size[0] / img.size[1] |
| 119 | if in_ratio < min(ratio): |
| 120 | w = img.size[0] |
| 121 | h = int(round(w / min(ratio))) |
| 122 | elif in_ratio > max(ratio): |
| 123 | h = img.size[1] |
| 124 | w = int(round(h * max(ratio))) |
| 125 | else: # whole image |
| 126 | w = img.size[0] |
| 127 | h = img.size[1] |
| 128 | i = (img.size[1] - h) // 2 |
| 129 | j = (img.size[0] - w) // 2 |
| 130 | return i, j, h, w |
| 131 | |
| 132 | def __call__(self, img): |
| 133 | """ |