Torchvision ToTensor, don't change channel order

When you use transforms.ToTensor(), by default it changes the input arrays from HWC to CHW order.

Is it possible to have ToTensor not do this if my input data are already in the ordering I want?

What can I replace this code with to make it keep the ordering I want and still convert to a torch tensor?



As there is no parameter in transforms.ToTensor() to control this behavior, the easiest and probably efficient way to solve this issue is to do what PyTorch have in its source code.

As you can see, it permutes the channels, So, same code can be used to reverse the order.

The reason that PyTorch is doing this is that, PyTorch uses CHW convention by default.


1 Like

Thanks for this. Just for the sake of containment if you want to reverse the order done by ToTensor, it would have to be img = img.permute((1, 2, 0)).contiguous(). The (2, 0, 1) is the forward transformation to go from HWC to CHW. To undo the operation, the tuple needs to be (1, 2, 0) instead.

Thanks again!

1 Like