Random crop the given PIL.Image to a random size of (0.08 to 1.0) of the original size and and a random aspect ratio of 3/4 to 4/3 of the original aspect ratio This is popularly used to train the Inception networks size: size of the smaller edge interpolation: Default: PIL.Image.BILI
| 207 | |
| 208 | |
| 209 | class GroupRandomSizedCrop(object): |
| 210 | """Random crop the given PIL.Image to a random size of (0.08 to 1.0) of the original size |
| 211 | and and a random aspect ratio of 3/4 to 4/3 of the original aspect ratio |
| 212 | This is popularly used to train the Inception networks |
| 213 | size: size of the smaller edge |
| 214 | interpolation: Default: PIL.Image.BILINEAR |
| 215 | """ |
| 216 | def __init__(self, size, interpolation=Image.BILINEAR): |
| 217 | self.size = size |
| 218 | self.interpolation = interpolation |
| 219 | |
| 220 | def __call__(self, img_group): |
| 221 | for attempt in range(10): |
| 222 | area = img_group[0].size[0] * img_group[0].size[1] |
| 223 | target_area = random.uniform(0.08, 1.0) * area |
| 224 | aspect_ratio = random.uniform(3. / 4, 4. / 3) |
| 225 | |
| 226 | w = int(round(math.sqrt(target_area * aspect_ratio))) |
| 227 | h = int(round(math.sqrt(target_area / aspect_ratio))) |
| 228 | |
| 229 | if random.random() < 0.5: |
| 230 | w, h = h, w |
| 231 | |
| 232 | if w <= img_group[0].size[0] and h <= img_group[0].size[1]: |
| 233 | x1 = random.randint(0, img_group[0].size[0] - w) |
| 234 | y1 = random.randint(0, img_group[0].size[1] - h) |
| 235 | found = True |
| 236 | break |
| 237 | else: |
| 238 | found = False |
| 239 | x1 = 0 |
| 240 | y1 = 0 |
| 241 | |
| 242 | if found: |
| 243 | out_group = list() |
| 244 | for img in img_group: |
| 245 | img = img.crop((x1, y1, x1 + w, y1 + h)) |
| 246 | assert(img.size == (w, h)) |
| 247 | out_group.append(img.resize((self.size, self.size), self.interpolation)) |
| 248 | return out_group |
| 249 | else: |
| 250 | # Fallback |
| 251 | scale = GroupScale(self.size, interpolation=self.interpolation) |
| 252 | crop = GroupRandomCrop(self.size) |
| 253 | return crop(scale(img_group)) |
| 254 | |
| 255 | |
| 256 | class Stack(object): |