# Program 10: Grayscale and RGB images - pixel values and colour channels

import cv2
import matplotlib.pyplot as plt

image = cv2.imread("photo.jpg")
rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
grey = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# One pixel: a colour pixel has three values, a grey pixel has one.
row, col = 150, 250
print("Pixel at row", row, "column", col)
print("  in the colour image (R, G, B) :", rgb[row, col])
print("  in the grayscale image        :", grey[row, col])
print()
print("Pixel values run from", grey.min(), "(black) to", grey.max(), "(white)")
print("Data type of each value :", grey.dtype, "(whole numbers 0 to 255)")
print()

# Split the colour image into its three channels.
red = rgb[:, :, 0]
green = rgb[:, :, 1]
blue = rgb[:, :, 2]
print("Average red value   :", round(red.mean(), 1))
print("Average green value :", round(green.mean(), 1))
print("Average blue value  :", round(blue.mean(), 1))

# To see one channel, keep it and set the other two channels to 0.
only_red = rgb.copy()
only_red[:, :, 1] = 0
only_red[:, :, 2] = 0
only_green = rgb.copy()
only_green[:, :, 0] = 0
only_green[:, :, 2] = 0
only_blue = rgb.copy()
only_blue[:, :, 0] = 0
only_blue[:, :, 1] = 0

plt.figure(figsize=(10, 3.6))
pictures = [rgb, grey, only_red, only_green, only_blue]
titles = ["Colour (RGB)", "Grayscale", "Red channel", "Green channel", "Blue channel"]
for i in range(5):
    plt.subplot(1, 5, i + 1)
    if i == 1:
        plt.imshow(pictures[i], cmap="gray")
    else:
        plt.imshow(pictures[i])
    plt.title(titles[i], fontsize=9)
    plt.axis("off")
plt.show()
