1
votes

I have been taking an online course in Python and I came across a line of code that I am unable to explain. I am trying to compute the sum of the red, green and blue channels of an image and the line of code to do so is:

img = plt.imread('480px-Astronaut-EVA.jpg') intensity = img.sum(axis=2)

Why is axis=2 used to sum up the values of all the three channels? I am using the matplotlib library.

4
what is img? what library are you using? - iamanigeeit
@iamanigeeit Sorry for not bring clear. I have edited my question. - Ruven Guna

4 Answers

2
votes

I found the original code that you are talking about. I assume it's :

import matplotlib.pyplot as plt

# Load the image into an array: img
img = plt.imread('myImage.jpg')

# Print the shape of the image
print(img.shape)  # Outputs : (480, 480, 3)

Then it calculates the sum of intensities over the third channel.

Remember the axes are : 0, 1 and 2.

# Compute the sum of the red, green and blue channels: intensity
intensity = img.sum(axis=2)

If you print the shape of the intensity :

# Print the shape of the intensity
print(intensity.shape)  # Output : (480, 480)

This means that for each couple of position (axe0_point, axe1_point), you sum the values of the axe 2.

For example, if img[50,50] == [10,10,10], you'll have intensity[50,50] = 30

1
votes

axis=2 (third axis) directs to sum the color components:

B = image[:,:,0]; G = image[:,:,1]; R = image[:,:,2]
0
votes

From the documentation:

For RGB images, the return value is MxNx3.

This means the image is stored as an MxN array of pixels with each pixel having a 3-tuple (the R, G, B values). img.sum(axis=2) means add up the 3rd axis (the RGB values) for each pixel, returning a MxN array of intensity values.

0
votes

The image is read into from file into an numpy array. You can get the whole idea of axis and data manipulation by reading article Numpy sum axis intuition (especially the examples):

The way to understand the “axis” of numpy sum is it collapses the specified axis. So when it collapses the axis 0 (row), it becomes just one row and column-wise sum.

In 2-d arrays, it might be confusing, however when we talk about 3-d, 4-d, n-d, it’s the more straightforward way to define the axis.