PyTorch Channels and Colour
A colour image is a tensor with three channels, one each for red, green, and blue. A greyscale image has one channel, and it holds brightness alone.
One channel or three
The channel count is the first number of the shape. It separates greyscale from colour.
import torch
grey = torch.zeros(1, 6, 6)
colour = torch.zeros(3, 6, 6)
print(grey.shape)
print(colour.shape)Splitting and restacking
Indexing reads one channel. Stacking the channels in order rebuilds the same image.
import torch
image = torch.arange(54, dtype=torch.float32).reshape(3, 3, 6)
red = image[0]
print(red.shape)
rebuilt = torch.stack([image[0], image[1], image[2]])
print(torch.equal(rebuilt, image))One averaged pixel
Averaging red 1.0, green 0.0, and blue 0.5 gives one brightness value.
import torch
pixel = torch.tensor([1.0, 0.0, 0.5])
print(pixel.mean())Example
import torch
# A tiny colour image: 3 channels, 6 rows, 6 columns.
image = torch.zeros(3, 6, 6)
image[0] = torch.linspace(0.0, 1.0, 6).reshape(-1, 1).expand(6, 6).clone()
image[1] = torch.linspace(0.0, 1.0, 6).reshape(1, -1).expand(6, 6).clone()
checker = torch.tensor([[1.0 if (r + c) % 2 == 0 else 0.2
for c in range(6)] for r in range(6)])
image[2] = checker
shades = " .:-=+*#%@"
def show(name, channel):
print(name)
for row in channel:
print("".join(shades[min(int(v.item() * 10), 9)] for v in row))
show("Red channel:", image[0])
show("Green channel:", image[1])
show("Blue channel:", image[2])
grey = image.mean(dim=0)
show("Channels averaged:", grey)Key points
- Greyscale: one channel that holds brightness only
- Colour: three channels that hold red, green, and blue amounts
- Use image[0], image[1], and image[2] to read the red, green, and blue channels
- Averaging the three channels gives a greyscale version of the image
- Channel order matters, because a reader expects red first and blue last
- Swapping two channels changes the colours, even though every number stays the same
- Three channels carry colour, and one channel carries brightness alone
In this example, the program builds a tiny colour image with 3 channels and 6 rows and 6 columns. The red channel rises from dark at the top to bright at the bottom. The green channel rises from dark at the left to bright at the right. The blue channel is a checker of bright and dim pixels. Each channel prints as its own shade grid. The last grid averages the three channels pixel by pixel. The averaged grid mixes all three patterns, and it holds brightness alone.
Note
A greyscale image saved with shape (1, height, width) still keeps its channel position
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What does averaging the three channels of a colour image produce?