Question

Please write a code in python! Define and test a function named posterize. This function expects...

Please write a code in python!

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.

images.py

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 + "\n")
rep += ("Width: " + str(self.width) + \
"\nHeight: " + str(self.height))
return rep
      
_root = tk.Tk()
_root.withdraw()

posterize.py

from images import Image


""" Write your code here """
def posterize(image, colorTup):
picture = image.open("picture.png")
gray_scale = picture.content('L')
dat = numpy.asarray(gray).copy()
dat[dat < 128] = 0
dat[dat >= 128] = 125
infinite = image.fromarray(dat)
infile.save("result_dat.png")

  

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()

smokey.gif

(is only a gif)

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Here is code for posterize function:

It's a very simple code, It takes RGBtuple and image as arguments. and converted into the black and white images using current RGB value by taking the average.

Add a comment
Know the answer?
Add Answer to:
Please write a code in python! Define and test a function named posterize. This function expects...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Please assist. I keep getting the error message in the middle screen when I run the...

    Please assist. I keep getting the error message in the middle screen when I run the program on the left. The image on the right is the section of images.py where it's indicating the issue with the .split is. How do I fix this? images.cy - /Users/carrietarpy Downloads/lab9-3/images.py 12.7.18) Python 2.7.18 Shell Python 2.7.15 (v2.7.18:542 102112, Apr 19 2820, 29:48:48) [GCC 4.7.1 Compatible Apple II w 6.3 Clong-FA3.0.57)] on der in Type "help", "copyright', 'credits' or "license()' for more inforyotion...

  • Encoding and Decoding PPM image 3 & 4 are parts of question 2 Code for a09q1:...

    Encoding and Decoding PPM image 3 & 4 are parts of question 2 Code for a09q1: We were unable to transcribe this image3 Encoding an Image in a09q2.py In the next four sections, you will no longer write class methods but rather functions. In each of the next four parts, you should be importing the PPM class from a09q1.py to use with the command from a09q1 import PPM Note that this is similar to how the check module was imported...

  • Please use python. You can import only: from typing import Dict, List from PIL import Image...

    Please use python. You can import only: from typing import Dict, List from PIL import Image import random Questions are: --------------------------------------------------------------------------------------------------------------------------------- 1. def rotate_picture_90_left(img: Image) -> Image: """Return a NEW picture that is the given Image img rotated 90 degrees to the left. Hints: - create a new blank image that has reverse width and height - reverse the coordinates of each pixel in the original picture, img, and put it into the new picture """ -----------------------------------------------------------------------------------------------------------------------------------    2. def...

  • def blur(img: Image) -> Image: """Blur Image, img, based on the given pixel_size Hints: - For...

    def blur(img: Image) -> Image: """Blur Image, img, based on the given pixel_size Hints: - For each pixel, calculate average RGB values of its neighbouring pixels (i.e. newRed = average of all the R values of each adjacent pixel, ...) - Set the RGB value of the center pixel to be the average RGB values of all the pixels around it Be careful at the edges of the image: not all pixels have 8 neighboring pixels! """ please use python...

  • Python Project

    AssignmentBitmap files map three 8-bit (1-byte) color channels per pixel. A pixel is a light-emitting "dot" on your screen. Whenever you buy a new monitor, you will see the pixel configuration by its width and height, such as 1920 x 1080 (1080p) or 3840x2160 (4K). This tells us that we have 1080 rows (height), and each row has 1920 (width) pixels.The bitmap file format is fairly straight forward where we tell the file what our width and height are. When...

  • PYTHON The provided code in the ATM program is incomplete. Complete the run method of the...

    PYTHON The provided code in the ATM program is incomplete. Complete the run method of the ATM class. The program should display a message that the police will be called after a user has had three successive failures. The program should also shut down the bank when this happens. [comment]: <> (The ATM program allows a user an indefinite number of attempts to log in. Fix the program so that it displays a message that the police will be called...

  • Python only please, thanks in advance. Type up the GeometricObject class (code given on the back...

    Python only please, thanks in advance. Type up the GeometricObject class (code given on the back of the paper). Name this file GeometricObjectClass and store it in the folder you made (xxlab14) 1. Design a class named Rectangle as a subclass of the GeometricObject class. Name the file RectangleClass and place it in the folder. 2. The Rectangle class contains Two float data fields named length and width A constructor that creates a rectangle with the specified fields with default...

  • Assignment Λ You shall write a Java program that accepts 5 command-line arguments and generates an image of a Sierpinski triangle, as a 24- bit RGB PNG image file. Specifications The command-line arg...

    Assignment Λ You shall write a Java program that accepts 5 command-line arguments and generates an image of a Sierpinski triangle, as a 24- bit RGB PNG image file. Specifications The command-line arguments shall consist of the following 1. The width (in pixels) of the image, as a positive decimal integer 2. The height (in pixels) of the image, as a positive decimal integer 3. The minimum area (in pixels) that a triangle must have in order to be drawn,...

  • the following python code edits BMP image file to negative but I need help with modifying...

    the following python code edits BMP image file to negative but I need help with modifying this code so it turns it the same BMP image file into a black and white instead of a negative. heres python code I have so far [pasted below] ## # This program processes a digital image by creating a negative of a BMP image. # from io import SEEK_CUR from sys import exit def main() : filename = input("Please enter the file name:...

  • can someone please help me write a python code for this urgently, asap Question: Write a Python function, minmp,...

    can someone please help me write a python code for this urgently, asap Question: Write a Python function, minmp, that is passed a file name and a metal alloy's formula unit structure*". The file will contain metal elements and their properties. The function will return a tuple of the element from the formula with the lowest melting point and that melting point Write a second function, molform, that will be called by the first function, to take the metal alloy's...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT