Home > Blockchain >  python function to change RGB values of an image
python function to change RGB values of an image

Time:02-28

I have this function that solely displays the red RGB values of an image. However, I am confused about how the function works. Specifically, why is there a 0 in brackets in this line:

newimage[i][j] = [image[i][j][0], 0, 0]

How can I alter this function to swap the green and blue RGB values while keeping the red value the same?

from matplotlib.pyplot import imshow #command to display a 2D array as an image
from imageio import imread #command to read images from a file or url

coffee = imread('imageio:coffee.png') #Image

def RedImage(image):
    newimage = ArrayOfZeros(400, 600)
    for i in range(400):
        for j in range(600):
            newimage[i][j] = [image[i][j][0], 0, 0]
    return newimage

imshow(RedImage(coffee))

CodePudding user response:

In

newimage[i][j] = [image[i][j][0], 0, 0]

image[i][j] and newimage[i][j] presumably are arrays consisting of three values for red, green, and blue at a particular pixel location (i, j) in the image.

So image[i][j][0] is the red value of the original image which will also be used as the red value for the new image. The blue and green values of the new image will be 0.

The green value of the original image is image[i][j][1] and the blue value is image[i][j][2]. So in order to swap them in the new image, use the green value of the old image in the position of the blue value for the new image, and the blue value of the old image in the position of the green value for the new image.

newimage[i][j] = [image[i][j][0], image[i][j][2], image[i][j][1]]
  • Related