In: Computer Science
Define a function named posterize. This function expects an image and a tuple of RGB values as arguments. The function modifies the image like the blackAndWhite function developed in Chapter 7 and shown below, but it uses passed in RGB values instead of black.
def blackAndWhite(image): """Converts the argument image to black and white.""" blackPixel = (0, 0, 0) whitePixel = (255, 255, 255) for y in range(image.getHeight()): for x in range(image.getWidth()): (r, g, b) = image.getPixel(x, y) average = (r + g + b) // 3 if average < 128: image.setPixel(x, y, blackPixel) else: image.setPixel(x, y, whitePixel)
An example of the program is shown below:
"""
File: posterize.py
Project 7.5
Defines and tests a function for posterizing images.
"""
from images import Image
""" Write your code here """
def main():
filename = input("Enter the image file name: ")
red = int(input("Enter an integer [0..255] for red: "))
green = int(input("Enter an integer [0..255] for green: "))
blue = int(input("Enter an integer [0..255] for blue: "))
image = Image(filename)
posterize(image, (red, green, blue))
image.draw()
if __name__ == "__main__":
main()
I hope you are asking for a function , that can explicitly set the RGB values for the input image, (if I am wrong in this statement, post a comment below, I will help based on that)
The required function is :(updated code),
I really want say, l sont the library you are usinh, Image. Intrsad I used teh opensourse project
from PIL import Image
def posterize(image, rgb_values):
'''Converts the argument image to the pixels passed'''
# for y in range(image.height):
# for x in range(image.width):
# # image.setPixel(x, y, rgb_values) # directly put the required rgb tuple in the current pixel position
# image.putpixel((x,y),rgb_values)
whitePixel = (255, 255, 255)
for y in range(image.getHeight()):
for x in range(image.getWidth()):
(r, g, b) = image.getPixel(x, y)
average = (r + g + b) // 3
if average < 128:
image.setPixel(x, y, rgb_values)
else:
image.setPixel(x, y, whitePixel)
return image
def main():
# filename = input("Enter the image file name: ")
# red = int(input("Enter an integer [0..255] for red: "))
# green = int(input("Enter an integer [0..255] for green: "))
# blue = int(input("Enter an integer [0..255] for blue: "))
filename = 'panda.jpg'
red = 100
green = 100
blue = 100
image = Image.open(filename)
posterize(image, (red, green, blue))
# image.draw()
if __name__ == "__main__":
main()
Screenshot of the code : ( to understand the indentation)