| 200 | |
| 201 | |
| 202 | class SlidingCrop(object): |
| 203 | def __init__(self, crop_size, stride_rate, ignore_label): |
| 204 | self.crop_size = crop_size |
| 205 | self.stride_rate = stride_rate |
| 206 | self.ignore_label = ignore_label |
| 207 | |
| 208 | def _pad(self, img, mask): |
| 209 | h, w = img.shape[: 2] |
| 210 | pad_h = max(self.crop_size - h, 0) |
| 211 | pad_w = max(self.crop_size - w, 0) |
| 212 | img = np.pad(img, ((0, pad_h), (0, pad_w), (0, 0)), 'constant') |
| 213 | mask = np.pad(mask, ((0, pad_h), (0, pad_w)), 'constant', constant_values=self.ignore_label) |
| 214 | return img, mask, h, w |
| 215 | |
| 216 | def __call__(self, img, mask): |
| 217 | assert img.size == mask.size |
| 218 | |
| 219 | w, h = img.size |
| 220 | long_size = max(h, w) |
| 221 | |
| 222 | img = np.array(img) |
| 223 | mask = np.array(mask) |
| 224 | |
| 225 | if long_size > self.crop_size: |
| 226 | stride = int(math.ceil(self.crop_size * self.stride_rate)) |
| 227 | h_step_num = int(math.ceil((h - self.crop_size) / float(stride))) + 1 |
| 228 | w_step_num = int(math.ceil((w - self.crop_size) / float(stride))) + 1 |
| 229 | img_slices, mask_slices, slices_info = [], [], [] |
| 230 | for yy in range(h_step_num): |
| 231 | for xx in range(w_step_num): |
| 232 | sy, sx = yy * stride, xx * stride |
| 233 | ey, ex = sy + self.crop_size, sx + self.crop_size |
| 234 | img_sub = img[sy: ey, sx: ex, :] |
| 235 | mask_sub = mask[sy: ey, sx: ex] |
| 236 | img_sub, mask_sub, sub_h, sub_w = self._pad(img_sub, mask_sub) |
| 237 | img_slices.append(Image.fromarray(img_sub.astype(np.uint8)).convert('RGB')) |
| 238 | mask_slices.append(Image.fromarray(mask_sub.astype(np.uint8)).convert('P')) |
| 239 | slices_info.append([sy, ey, sx, ex, sub_h, sub_w]) |
| 240 | return img_slices, mask_slices, slices_info |
| 241 | else: |
| 242 | img, mask, sub_h, sub_w = self._pad(img, mask) |
| 243 | img = Image.fromarray(img.astype(np.uint8)).convert('RGB') |
| 244 | mask = Image.fromarray(mask.astype(np.uint8)).convert('P') |
| 245 | return [img], [mask], [[0, sub_h, 0, sub_w, sub_h, sub_w]] |
nothing calls this directly
no outgoing calls
no test coverage detected