Finding RGB values

2.2k Views Asked by At

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

There are 2 best solutions below

0
On BEST ANSWER

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
On

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]