# Best way to downsample-batch image tensors

**URL:** <https://discuss.pytorch.org/t/best-way-to-downsample-batch-image-tensors/114952>\
**Category:** vision\
**Created:** [March 16, 2021, 6:57am UTC](https://discuss.pytorch.org/t/best-way-to-downsample-batch-image-tensors/114952 "2021-03-16T06:57:22Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Hyung\_Jin\_Chung](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/hyung_jin_chung/32/10324_2.png) [@Hyung\_Jin\_Chung](https://discuss.pytorch.org/u/Hyung_Jin_Chung)\
**Post date:** [March 16, 2021, 6:57am UTC](https://discuss.pytorch.org/t/best-way-to-downsample-batch-image-tensors/114952/1 "2021-03-16T06:57:22Z")

</div>

Say you have a gray image tensor of shape `(1, 1, 128, 128) `. What I would like to do here is to sample in each `h, w `dimension with `stride=2`, which would then make 4 sub-images of size `(1, 1, 64, 64)` depending on where the indexing starts. Then, I would like to batch them to finally form the tensor of size `(4, 1, 64, 64)`. For now, I’m using double for loops which is presumably inefficient. Is there an efficient way to vectorize this using functions implemented in pytorch?

The function I’m using right now:

```auto
def img_subsample(img, ratio=2):
    '''
    ex) Subsamples img of size 128 * 128,
    output is batched into 4 * 1 * 64 * 64
    Args:
        img: input of size ex) 128 * 128
        ratio(int): Subsampling ratio
    Returns: batched, subsampled img
    '''
    sz = img.shape[-1]
    batched_output = torch.zeros([ratio**2, 1, (sz//ratio), (sz//ratio)])
    for i in range(ratio):
        for j in range(ratio):
            batched_output[ratio*i+j, :, :, :] = img[i::ratio, j::ratio]
    return batched_output

```

---

<div class="post-metadata">

**Author:** ![Naruto-Sasuke](https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/n/ed8c4c/32.png) [@Naruto-Sasuke](https://discuss.pytorch.org/u/Naruto-Sasuke)\
**Post date:** [March 16, 2021, 7:57am UTC](https://discuss.pytorch.org/t/best-way-to-downsample-batch-image-tensors/114952/2 "2021-03-16T07:57:34Z")

</div>

Refer to nn.PixelShuffle()

---

<div class="post-metadata">

**Author:** ![Sunshine352](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/sunshine352/32/7667_2.png) [@Sunshine352](https://discuss.pytorch.org/u/Sunshine352)\
**Post date:** [March 16, 2021, 9:12am UTC](https://discuss.pytorch.org/t/best-way-to-downsample-batch-image-tensors/114952/3 "2021-03-16T09:12:02Z")

</div>

`torch.nn.functional.` `unfold` (_input_, _kernel\_size_, _dilation=1_, _padding=0_, _stride=1_ )[[SOURCE]](https://pytorch.org/docs/1.0.0/_modules/torch/nn/functional.html#unfold)

Extracts sliding local blocks from an batched input tensor.

WARNING

Currently, only 4-D input tensors (batched image-like tensors) are supported.

See [`torch.nn.Unfold`](https://pytorch.org/docs/1.0.0/nn.html?highlight=fold#torch.nn.Unfold) for details
