Grayscale to RGB transform

You can also convert a 2D grayscale image to a 3D RGB one by doing:

img = img.view(width, height, 1).expand(-1, -1, 3)

Calling .repeat will actually replicate the image data (taking 3x the memory of the original image) whereas .expand will behave as if the data is replicated without actually doing so. Thus .expand is probably better unless you want to change the channels independently of each other.

4 Likes