# How to resize and pad in a torchvision.transforms.Compose()?

**URL:** <https://discuss.pytorch.org/t/how-to-resize-and-pad-in-a-torchvision-transforms-compose/71850>\
**Category:** vision\
**Created:** [March 3, 2020, 2:38pm UTC](https://discuss.pytorch.org/t/how-to-resize-and-pad-in-a-torchvision-transforms-compose/71850 "2020-03-03T14:38:28Z")\
**Posts on this page:** 1\
**Showing post:** 5

<div class="post-metadata">

**Author:** ![weisunding](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/weisunding/32/27081_2.png) [@weisunding](https://discuss.pytorch.org/u/weisunding)\
**Post date:** [July 24, 2020, 3:20pm UTC](https://discuss.pytorch.org/t/how-to-resize-and-pad-in-a-torchvision-transforms-compose/71850/5 "2020-07-24T15:20:31Z")

</div>

This post saved my day, thanks! For simplicity, forget about the odd/even value of the image width/height is OK, the simplified code.

```auto
import torchvision.transforms.functional as F

class SquarePad:
	def __call__ (self, image):
		w, h = image.size
		max_wh = np.max([w, h])
		hp = int((max_wh - w) / 2)
		vp = int((max_wh - h) / 2)
		padding = (hp, vp, hp, vp)
		return F.pad(image, padding, 0, 'constant')

# now use it as the replacement of transforms.Pad class
transform=transforms.Compose([
    SquarePad(),
    transforms.Resize(image_size),
    transforms.CenterCrop(image_size),
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])

```

---

_[View the full topic](https://discuss.pytorch.org/t/how-to-resize-and-pad-in-a-torchvision-transforms-compose/71850)._
