0
votes

I want to write a function that prints out the color values, RGB, of a picture. The pictures are either colored all red, green, yellow or white.

What I have is the following:

def findColor():
    pic=takePicture()
    red = 0   
    green = 0
    blue = 0 
    size = getWidth(pic)*getHeight(pic)
    for pix in getPixels(pic):
        r = getRed(pix)
        g = getGreen(pix)
        b = getBlue(pix)
        red = red + r
        green = green + g
        blue = blue + b 
    print(red//size,green//size,blue//size)

Or a code that gives me similar values as above:

def findColor():
    pic=takePicture()
    for pix in getPixels(pic):
        r = getRed(pix)
        g = getGreen(pix)
        b = getBlue(pix)
    print(r,g,b)   

Are these codes a correct way of getting the RGB values? I believe the second code isn't accurate if the picture contained different colors.

2
"Are these codes a correct way of getting the RGB values?" Let me answer that question with another question. When you run them, do you get the output that you want?Kevin
@Kevin Yes, if I set restrictions like the pictures I linked. And no, if the restrictions aren't there, for example if the picture was a mixture of red, black and purple. I will like to know if the first code is the correct way.Robben
The first one prints the average of all pixels in the image. The second one prints the color of the bottom-right pixel in the image. If your image contains exactly one color, then they'll both print the same thing.Kevin
@Kevin Hm, so the correct way of finding the RGB values will then be my first code?Robben
It's not clear to me what "finding the RGB values" means, so I can't really answer that.Kevin

2 Answers

1
votes

If you just want to print the rgb value for each individual pixel, your second code block will work if you fix the indentation.

def findColor():
    pic=takePicture()
    for pix in getPixels(pic):
        r = getRed(pix)
        g = getGreen(pix)
        b = getBlue(pix)
        print(r,g,b) 
0
votes

Many be late for the original post.

In case the pic is a ndarray with shape like (R,C,3) R-> Rows/Height , C -> Columns/Width and 3 channels (RGB)

This article Python numpy array with multiple conditions to iterate over image is the one line solution you might be searching for

Red,Green,Blue = img[...,0],img[...,1],img[...,2]