def inverse(self): if not self._can_invert(): raise InvertibleError('Cannot invert a transformation before it is applied' ' (size before the cropping is unknown).') crop_h, crop_w = self.size pad_w = self._img_w - crop_w pad_h = self._img_h - crop_h pad_tl = (0, 0, pad_w, pad_h) pad_tr = (pad_w, 0, 0, pad_h) pad_bl = (0, pad_h, pad_w, 0) pad_br = (pad_w, pad_h, 0, 0) half_w = (self._img_w - crop_w) // 2 half_h = (self._img_h - crop_h) // 2 pad_center = (half_w, half_h, self._img_w - crop_w - half_w, self._img_h - crop_h - half_h) tfs = [] for padding in [pad_tl, pad_tr, pad_bl, pad_br, pad_center]: tf = T.Pad(padding) tf._img_h = crop_h tf._img_w = crop_w tfs.append(tf) def invert_crops(crops): tl, tr, bl, br, center = crops return [tf(img) for tf, img in zip(tfs, [tl, tr, bl, br, center])] def invert_invert_crops(crops): tl, tr, bl, br, center = crops return [tf.inverse()(img) for tf, img in zip(tfs, [tl, tr, bl, br, center])] return T.Lambda( lambd=invert_crops, tf_inv=invert_invert_crops, repr_str=f'FiveCropInverse()', )
def test_padding_int(self): padding = 100 tf = T.Pad(padding=padding) img_inv = tf(self.img_pil) self.assertEqual(img_inv.size, (self.w + 2 * padding, self.h + 2 * padding)) self.assertEqual(self.img_pil.size, tf.invert(img_inv).size)
def test_padding_mismatch(self): tf = T.Pad(0) tf.padding = None tf._img_h, tf._img_w = self.img_size with self.assertRaises(Exception): tf.inverse()
def test_invert_before_call(self): with self.assertRaises(InvertibleError): T.Pad(0).inverse()
def test_padding_tuple(self): pad_lr, pad_tb = 100, 50 tf = T.Pad(padding=(pad_lr, pad_tb)) img_inv = tf(self.img_pil) self.assertEqual(img_inv.size, (self.w + 2 * pad_lr, self.h + 2 * pad_tb)) self.assertEqual(self.img_pil.size, tf.invert(img_inv).size)