# Img2col operation in Pytorch

**URL:** <https://discuss.pytorch.org/t/img2col-operation-in-pytorch/17750>\
**Category:** Uncategorized\
**Created:** [May 8, 2018, 4:01pm UTC](https://discuss.pytorch.org/t/img2col-operation-in-pytorch/17750 "2018-05-08T16:01:56Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![lxtGH](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/lxtgh/32/3711_2.png) [@lxtGH](https://discuss.pytorch.org/u/lxtGH)\
**Post date:** [May 8, 2018, 4:01pm UTC](https://discuss.pytorch.org/t/img2col-operation-in-pytorch/17750/1 "2018-05-08T16:01:56Z")

</div>

Has anyone know this operation in Pytorch ?

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [May 8, 2018, 4:14pm UTC](https://discuss.pytorch.org/t/img2col-operation-in-pytorch/17750/2 "2018-05-08T16:14:31Z")

</div>

What is your use case?  
Maybe you could use [tensor.unfold](https://pytorch.org/docs/stable/tensors.html#torch.Tensor.unfold)?

---

<div class="post-metadata">

**Author:** ![lxtGH](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/lxtgh/32/3711_2.png) [@lxtGH](https://discuss.pytorch.org/u/lxtGH)\
**Post date:** [May 8, 2018, 4:17pm UTC](https://discuss.pytorch.org/t/img2col-operation-in-pytorch/17750/3 "2018-05-08T16:17:56Z")

</div>

For example, I want to make one tensor (n,c,w,h) into tensor (n,c,w,h, k\*k) where k is the kernel size  
use img2col (like caffe) operation to do this.

---

<div class="post-metadata">

**Author:** ![ptrblck](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/ptrblck/32/1823_2.png) [@ptrblck](https://discuss.pytorch.org/u/ptrblck)\
**Post date:** [May 9, 2018, 1:20am UTC](https://discuss.pytorch.org/t/img2col-operation-in-pytorch/17750/4 "2018-05-09T01:20:27Z")

</div>

If you would like to use a sliding window of kernel size `k`, you could try the following code (originally created by @fmassa) :

```auto
n, c, w, h = 1, 3, 24, 24
k = 3
stride = 1
x = torch.randn(n, c, w, h)
input_windows = x.unfold(2, k, stride).unfold(3, k, stride)
print(input_windows.shape)
> torch.Size([1, 3, 22, 22, 3, 3])
input_windows = input_windows.contiguous().view(*input_windows.size()[:-2], -1)
print(input_windows.shape)
> torch.Size([1, 3, 22, 22, 9])

```

Your width and height will be smaller as in a vanilla convolution without padding.

---

<div class="post-metadata">

**Author:** ![lxtGH](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/lxtgh/32/3711_2.png) [@lxtGH](https://discuss.pytorch.org/u/lxtGH)\
**Post date:** [May 9, 2018, 6:25am UTC](https://discuss.pytorch.org/t/img2col-operation-in-pytorch/17750/5 "2018-05-09T06:25:48Z")

</div>

Thank you very much !!!
