Question
Define and test a function named posterize. This function expects an image and a tuple of RGB values as arguments. The function modifies the image
Define and test 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, but it uses the given RGB values instead of black.
here is the blackandwhite function
here is the images.py file:
import Tkinter
import os, os.path
tk = Tkinter
_root = None
class ImageView(tk.Canvas):
def __init__(self, image,
title = "New Image",
autoflush=False):
master = tk.Toplevel(_root)
master.protocol("WM_DELETE_WINDOW", self.close)
tk.Canvas.__init__(self, master,
width = image.getWidth(),
height = image.getHeight())
self.master.title(title)
self.pack()
master.resizable(0,0)
self.image = image
self.height = image.getHeight()
self.width = image.getWidth()
self.autoflush = autoflush
self.closed = False
def close(self):
"""Close the window"""
self.closed = True
self.master.destroy()
self.image.canvas = None
_root.quit()
def isClosed(self):
return self.closed
def getHeight(self):
"""Return the height of the window"""
return self.height
def getWidth(self):
"""Return the width of the window"""
return self.width
class Image:
def __init__(self, *args):
self.canvas = None
if len(args) == 1:
name = args[0]
if type(name) != str:
raise Exception('Must be a file name')
if name[-4:].upper() != '.GIF':
raise Exception('File must be a GIF')
if not os.path.exists(args[0]):
raise Exception('File not in current directory')
self.image = tk.PhotoImage(file = args[0], master = _root)
self.filename = args[0]
self.width = self.image.width()
self.height = self.image.height()
else: # arguments are width and height
self.width, self.height = args
self.image = tk.PhotoImage(master =_root,
width = self.width,
height = self.height)
self.filename = ""
def getWidth(self):
"""Returns the width of the image in pixels"""
return self.width
def getHeight(self):
"""Returns the height of the image in pixels"""
return self.height
def getPixel(self, x, y):
"""Returns a tuple (r,g,b) with the RGB color values for pixel (x,y)
r,g,b are in range(256)
"""
value = self.image.get(x, y)
if type(value) == int:
return (value, value, value)
elif type(value) == tuple:
return value
else:
return tuple(map(int, value.split()))
def setPixel(self, x, y, color):
"""Sets pixel (x,y) to the color given by RGB values r, g, and b.
r,g,b should be in range(256)
"""
(r, g, b) = color
r = round(r)
g = round(g)
b = round(b)
color = (r, g, b)
self.image.put("{#%02x%02x%02x}" % color, (x, y))
def draw(self):
"""Creates and opens a window on an image.
The user must close the window to return control to
the caller."""
if not self.canvas:
self.canvas = ImageView(self,
self.filename)
self.canvas.create_image(self.width // 2,
self.height // 2,
image = self.image)
_root.mainloop()
def save(self, filename = ""):
"""Saves the image to filename. If no file name
is provided, uses the image's file name if there
is one; otherwise, simply returns.
If the .gif extension is not present, it is added.
"""
if filename == "":
return
else:
self.filename = filename
path, name = os.path.split(filename)
ext = name.split(".")[-1]
if ext != "gif":
filename += ".gif"
self.filename = filename
self.image.write(self.filename, format = "gif")
def clone(self):
new = Image(self.width, self.height)
new.image = self.image.copy()
return new
def __str__(self):
rep = ""
if self.filename:
rep += ("File name: " + self.filename + " ")
rep += ("Width: " + str(self.width) +
" Height: " + str(self.height))
return rep
_root = tk.Tk()
_root.withdraw()
6 from images import Image 8 def detectEdges (image, amount): ""Builds and returns a new image in which the edges of the argument image are highlighted and the colors are reduced to black and white.""n 13 def average(triple): (r, g, b) triple return (r + g + b) /3 16 blackPixel - (0, 0, 0) whitePixel-(255, 255, 255) newimage.clone() for y in range(image.getHeight() - 1): 20 21 for x in range(1, image.getWidth)): 23 24 25 26 27 28 29 30 31 32 oldPixel -image.getPixel(x, y) leftPixel-image.getPixel(x - 1, y) bottomPixel-image.getPixel(x, y + 1) oldLumaverage(oldPixel) leftLum average(leftPixel) bottomLumaverage(bottomPixel) if abs (oldLumleftLum) > amount or abs (oldLum -bottomLum) amount new.setPixel(x, y, blackPixel) else: new.setPixel(x, y, whitePixel) return new 34 35 def main(filename"smokey.gif"): 36 37 38 39 imageImage(filename) print ("Close the image window to continue.") image.draw() image2detectEdges (image, 10) print("Close the image window to continue. ") image2.draw() image3detectEdges (image, 20) print("Close the image window to continue. ") image3.draw() print("Close the image window to quit. ") 41 42 43 46 47 if__name_"__main__" 48 main() 6 from images import Image 8 def detectEdges (image, amount): ""Builds and returns a new image in which the edges of the argument image are highlighted and the colors are reduced to black and white.""n 13 def average(triple): (r, g, b) triple return (r + g + b) /3 16 blackPixel - (0, 0, 0) whitePixel-(255, 255, 255) newimage.clone() for y in range(image.getHeight() - 1): 20 21 for x in range(1, image.getWidth)): 23 24 25 26 27 28 29 30 31 32 oldPixel -image.getPixel(x, y) leftPixel-image.getPixel(x - 1, y) bottomPixel-image.getPixel(x, y + 1) oldLumaverage(oldPixel) leftLum average(leftPixel) bottomLumaverage(bottomPixel) if abs (oldLumleftLum) > amount or abs (oldLum -bottomLum) amount new.setPixel(x, y, blackPixel) else: new.setPixel(x, y, whitePixel) return new 34 35 def main(filename"smokey.gif"): 36 37 38 39 imageImage(filename) print ("Close the image window to continue.") image.draw() image2detectEdges (image, 10) print("Close the image window to continue. ") image2.draw() image3detectEdges (image, 20) print("Close the image window to continue. ") image3.draw() print("Close the image window to quit. ") 41 42 43 46 47 if__name_"__main__" 48 main()Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started