Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Image format from NHWC to NCHW for Pytorch

In pytorch we need images in NCHW format but my images are NHWC.

What is the procedure to feed this image to CNN? (I have found this solution which suggests to use "permute" but where and how should i use it?)

like image 604
shuvo Avatar asked Aug 16 '18 16:08

shuvo


People also ask

How do you convert NHWC to NCHW?

From NHWC to NCHW The image shape is (N, H, W, C) and we want the output to have shape (N, C, H, W) . Therefore we need to apply tf. transpose with a well chosen permutation perm .

Is PyTorch a NCHW?

Numpy uses NHWC, pytorch uses NCHW, all the conversion seems a bit confusing at times, why does Pytorch use NCHW at the very beginning? I think it was the default format in LuaTorch and I don't know, why this format was preferred over NHWC. However, note that PyTorch has now experimental channels-last support.

What is NCHW format?

NCHW stands for: batch N, channels C, depth D, height H, width W. It is a way to store multidimensional arrays / data frames / matrix into memory, which can be considered as a 1-D array.

What is NHWC format in TensorFlow?

Data Format NHWC (N, Height, width, channel) is the TensorFlow default and NCHW is the optimal format to use for NVIDIA cuDNN. If TensorFlow is compiled with the Intel MKL optimizations, many operations will be optimized and support NCHW. Otherwise, some operations are not supported on CPU when using NCHW.


1 Answers

Using torch.Tensor.permute():

 x = x.permute(0, 3, 1, 2) # from NHWC to NCHW
like image 78
benjaminplanche Avatar answered Oct 18 '22 01:10

benjaminplanche