Resize, center crop, convert to tensor, and normalize.
(self, img, oh, ow, normalize=True)
| 35 | return img |
| 36 | |
| 37 | def _resize_crop(self, img, oh, ow, normalize=True): |
| 38 | """ |
| 39 | Resize, center crop, convert to tensor, and normalize. |
| 40 | """ |
| 41 | # resize and crop |
| 42 | iw, ih = img.size |
| 43 | if iw != ow or ih != oh: |
| 44 | # resize |
| 45 | scale = max(ow / iw, oh / ih) |
| 46 | img = img.resize((round(scale * iw), round(scale * ih)), |
| 47 | resample=Image.Resampling.LANCZOS) |
| 48 | assert img.width >= ow and img.height >= oh |
| 49 | |
| 50 | # center crop |
| 51 | x1 = (img.width - ow) // 2 |
| 52 | y1 = (img.height - oh) // 2 |
| 53 | img = img.crop((x1, y1, x1 + ow, y1 + oh)) |
| 54 | |
| 55 | # normalize |
| 56 | if normalize: |
| 57 | img = TF.to_tensor(img).sub_(0.5).div_(0.5).unsqueeze(1) |
| 58 | return img |
| 59 | |
| 60 | def _image_preprocess(self, img, oh, ow, normalize=True, **kwargs): |
| 61 | return self._resize_crop(img, oh, ow, normalize) |