In: Computer Science
The main function creates 5 pixels with random red, green, and blue values. Complete the id_color function to return “red” if the red value is greater than the green and blue, “green” if the green value is greater than the red and blue, and “blue” if the blue value is greater than the red and green. If there is no clear maximum value (for example, if the red and green values are the same) return None. Do not change the main function.
import image
import random
def id_color(p):
'''Returns the dominant color of pixel p'''
pass
#Your code here to determine the dominant color and return a string
identifying it
#Hint: get the red, green & blue values and use an if statement
to determine which has the highest value
def main():
'''Controls the program'''
for i in range(5): #Loop 5 times
r = random.randrange(0, 256)
g = random.randrange(0, 256)
b = random.randrange(0, 256)
print(r, g, b) #Show the pixel red, green & blue values
new_pixel = image.Pixel(r, g, b)
print(id_color(new_pixel))
main() #Run the program
So you create a pixel inside the main function five times (using for loop) and you call the get_color(new_pixel) function to get the highest value i.e the dominant color out of Red, Green and Blue that every pixel has, so you call this function five times inside the for loop so you should get five strings as return values from the get_color function and you print it in the main function.
Upvote if you find this useful!
You can complete the get_color(new_pixel) function this way:
import PIL as Image
def id_color(p):
r,g,b=p.getpixel((1,1))
if r>g and r>b:
return "red"
elif g>b and g>r:
return "green"
elif b>r and b>g:
return "blue"
elif r==g and r>b:
return None
elif r==b and r>g:
return None
elif g==b and g>r:
return None
So the basic process is:
1. Get the RGB values of p i.e pixel value passed from main function using getpixel() function from PIL
2. Check if Red is greater than blue and green, if yes then return "red"
3.Check if Green is greater than blue and red, if yes return "green"
4. Check if Blue is greater than red and green, if yes return "blue"
5. Check if any two values are equal if yes then check if they are the largest if yes then return None