Question

from PIL import Image import random # NOTE: Feel free to add in any constant values...

from PIL import Image
import random

# NOTE: Feel free to add in any constant values you find useful to use
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)

# NOTE: Feel free to add in any helper functions to organize your code but
# do NOT rename any existing functions (or else, autograder
# won't be able to find them!!)


# NOTE: The following function is already completed for you as an example
# You can use the structure of this function as a guide for the rest
# This function will NOT be graded, so no need to edit any of it.
def remove_red(img: Image) -> Image:
"""
Given an Image, img, update the img to have all the reds in the original
image turned to 0 intensity. Return img.
"""

img_width, img_height = img.size
pixels = img.load() # create the pixel map

# for every pixel
for i in range(img_width):
for j in range(img_height):
r, g, b = pixels[i, j]
pixels[i, j] = (0, g, b)

return img

# NOTE: The following function is already completed for you as well
# This function will NOT be graded, so no need to edit any of it.
def scale_new_image(orig_img, goal_width: int = None, goal_height: int = None):
"""
Create and return a new image which resizes the given original Image,
orig_img to a the given goal_width and goal_height. If no goal dimensions
are provided, scale the image down to half its original width and height.
Return the new image.
"""
  
orig_width, orig_height = orig_img.size
orig_pixels = orig_img.load()
  
if not goal_width and not goal_height:
goal_width, goal_height = orig_width//2, orig_height//2
  
img = Image.new('RGB', (goal_width, goal_height))
new_pixels = img.load()

width_factor = goal_width / orig_width
height_factor = goal_height / orig_height

for i in range(goal_width):
for j in range(goal_height):
new_pixels[i, j] = orig_pixels[i // width_factor, j // height_factor]
return img


# NOTE: The following function is partially completed to get you started
# Complete the function according to the docstring description
def greyscale(img: Image) -> Image:
"""
Change the Image, img, to greyscale by taking the average color of each
pixel in the image and set the red, blue and green values of the pixel
with that average. Return img.
"""

img_width, img_height = img.size
pixels = img.load() # create the pixel map

# for every pixel
for i in range(img_width):
for j in range(img_height):

# YOUR CODE HERE -- delete these filler lines once you put your code in
pass

return img


# TODO: COMPLETE THE REST OF THE FUNCTIONS ACCORDING TO THEIR DOCSTRINGS
# NOTE: Remember, you can and should add in helper functions to organize
# your code, when applicable

def black_and_white(img: Image) -> Image:
"""
Given an Image, img, update the img to have ONLY black or white pixels.
Return img.

Hints:
- Get the average color of each pixel
- If the average is higher than the "middle" color (i.e. 255/2),
change it to white; if it's equal to or lower, change it to black
"""

# NOTE: Remove the "pass" placeholder when you put your own code in
pass


def sepia(img: Image) -> Image:
"""
Given an Image, img, update the img to have a sepia scheme.
Return img.

Hints:
- Get the RGB value of the pixel.
- Calculate newRed, newGree, newBlue using the formula below:
  
newRed = 0.393*R + 0.769*G + 0.189*B
newGreen = 0.349*R + 0.686*G + 0.168*B
newBlue = 0.272*R + 0.534*G + 0.131*B
(Take the integer value of each.)

If any of these output values is greater than 255, simply set it to 255.
These specific values are the recommended values for sepia tone.

- Set the new RGB value of each pixel based on the above calculations
(i.e. Replace the value of each R, G and B with the new value
that we calculated for the pixel.)
"""

# NOTE: Remove the "pass" placeholder when you put your own code in
pass


def normalize_brightness(img: Image) -> Image:
"""
Normalize the brightness of the given Image img by:
1. computing the average brightness of the picture:
- this can be done by calculating the average brightness of each pixel
in img (the average brightness of each pixel is the sum of the values
of red, blue and green of the pixel, divided by 3 as a float division)
- the average brightness of the picture is then the sum of all the
pixel averages, divided by the product of the width and hight of img

2. find the factor, let's call it x, which we can multiply the
average brightness by to get the value of 128

3. multiply the colors in each pixel by this factor x
"""

# NOTE: Remove the "pass" placeholder when you put your own code in
pass


def sort_pixels(img: Image) -> Image:
"""
Given an Image, img, sort (in non-descending order) each row of pixels
by the average of their RGB values. Return the updated img.

Tip: When testing this function out, first choose the greyscale
feature. This will make it easier to spot whether or not the pixels in each
row are actually sorted (it should go from darkest to lightest in a
black and white image, if the sort is working correctly).
"""
  
# NOTE: Remove the "pass" placeholder when you put your own code in
pass


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!
"""

# NOTE: Remove the "pass" placeholder when you put your own code in
pass


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
"""
  
# NOTE: Remove the "pass" placeholder when you put your own code in
pass


def rotate_picture_90_right(img: Image) -> Image:
"""
Return a NEW picture that is the given Image img rotated 90 degrees
to the right.
"""

# NOTE: Remove the "pass" placeholder when you put your own code in
pass


def flip_horizontal(img: Image) -> Image:
"""
Given an Image, img, update it so it looks like a mirror
was placed horizontally down the middle.

Tip: Remember Python allows you to switch values using a, b = b, a notation.
You don't HAVE to use this here, but it might come in handy.
"""

# NOTE: Remove the "pass" placeholder when you put your own code in
pass


def flip_vertical(img: Image) -> Image:
"""
Given an Image, img, update it so it looks like a mirror
was placed vertically down the middle.

Tip: Remember Python allows you to switch values using a, b = b, a notation.
You don't HAVE to use this here, but it might come in handy.
"""

# NOTE: Remove the "pass" placeholder when you put your own code in
pass


def kaleidoscope(img: Image) -> Image:
"""
Given an Image, img, update it to create a kaleidoscope.
You must maintain the size dimensions of the original image.
Return the updated img.

The kaleidoscope effect should have this image repeated four times:
- the original image will be in the lower left quadrant
- the lower right will be the original image flipped on the vertical axis
- the two top images will be the bottom two images flipped on the horizontal axis
  
Tip: You may want to use helper functions to organize the code here.
This filter can be broken down into a series of other operations, such as
flip vertical / horizontal, scale / downscale, etc.
"""

# NOTE: Remove the "pass" placeholder when you put your own code in
pass


def draw_border(img: Image) -> Image:
"""
Given an Image, img, update it to have a five pixel wide black border
around the edges. Return the updated img.
"""

# NOTE: Remove the "pass" placeholder when you put your own code in
pass

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

ANSWER:

  • As per Chegg Rules, I am bound to solve only the first four parts of the question having multiple parts. As your question consist of several function, I have provided the solution for first four unanswered functions i.e. greyscale(), black_and_white(), sepia() and normalize_brightness().
  • I have provided the properly commented code in both text and image format so it will be easy for you to copy the code as well as check for correct indentation of the code.
  • I have provided Input/Output image of the code so it will be easy for you to cross-check for correct output of the code.
  • Have a nice and healthy day!!

CODE TEXT

from PIL import Image
import random

# NOTE: The following function is partially completed to get you started
# Complete the function according to the docstring description
def greyscale(img: Image) -> Image:
"""
Change the Image, img, to greyscale by taking the average color of each
pixel in the image and set the red, blue and green values of the pixel
with that average. Return img.
"""
  
img_width, img_height = img.size
pixels = img.load() # create the pixel map
  
# for every pixel
for i in range(img_width):
for j in range(img_height):
## finding mean of rgb values, by dividing their sum by 3 and fetching int value
avg_pixel = sum(pixels[i,j])//3
## changing rgb values to avg_pixel in imag
pixels[i,j]= (avg_pixel,avg_pixel,avg_pixel)
  
return img


# TODO: COMPLETE THE REST OF THE FUNCTIONS ACCORDING TO THEIR DOCSTRINGS
# NOTE: Remember, you can and should add in helper functions to organize
# your code, when applicable

def black_and_white(img: Image) -> Image:
"""
Given an Image, img, update the img to have ONLY black or white pixels.
Return img.
  
Hints:
- Get the average color of each pixel
- If the average is higher than the "middle" color (i.e. 255/2),
change it to white; if it's equal to or lower, change it to black
"""
## fetching width and height of image
img_width, img_height = img.size
## fetching pixels map from image
pixels = img.load() # create the pixel map
  
# for every pixel
for i in range(img_width):
for j in range(img_height):
## finding mean of rgb values, by dividing their sum by 3
avg_pixel = sum(pixels[i,j])/3
## if mean is higher than 255/2
if avg_pixel>(255/2):
## changing pixel to white
pixels[i,j]= (255,255,255)
else: ## else
## changing pixel to black
pixels[i,j]= (0,0,0)
  
return img


def sepia(img: Image) -> Image:
"""
Given an Image, img, update the img to have a sepia scheme.
Return img.
  
Hints:
- Get the RGB value of the pixel.
- Calculate newRed, newGree, newBlue using the formula below:
  
newRed = 0.393*R + 0.769*G + 0.189*B
newGreen = 0.349*R + 0.686*G + 0.168*B
newBlue = 0.272*R + 0.534*G + 0.131*B
(Take the integer value of each.)
  
If any of these output values is greater than 255, simply set it to 255.
These specific values are the recommended values for sepia tone.
  
- Set the new RGB value of each pixel based on the above calculations
(i.e. Replace the value of each R, G and B with the new value
that we calculated for the pixel.)
"""
## fetching width and height of image
img_width, img_height = img.size
## fetching pixels map from image
pixels = img.load() # create the pixel map
  
# for every pixel
for i in range(img_width):
for j in range(img_height):
R,G,B=pixels[i,j]
## calculating newRed, newGreen, newBlue and converting them to int
newRed = int(0.393*R + 0.769*G + 0.189*B)
# checking if newRed>255
if newRed>255:
newRed=255
newGreen = int(0.349*R + 0.686*G + 0.168*B)
# checking if newRed>255
if newGreen>255:
newGreen=255
newBlue = int(0.272*R + 0.534*G + 0.131*B)
# checking if newRed>255
if newBlue>255:
newBlue=255
## Seting new pixels to image
pixels[i,j]= (newRed,newGreen,newBlue)
  
return img


def normalize_brightness(img: Image) -> Image:
"""
Normalize the brightness of the given Image img by:
1. computing the average brightness of the picture:
- this can be done by calculating the average brightness of each pixel
in img (the average brightness of each pixel is the sum of the values
of red, blue and green of the pixel, divided by 3 as a float division)
- the average brightness of the picture is then the sum of all the
pixel averages, divided by the product of the width and hight of img
  
2. find the factor, let's call it x, which we can multiply the
average brightness by to get the value of 128
  
3. multiply the colors in each pixel by this factor x
"""
## fetching width and height of image
img_width, img_height = img.size
## fetching pixels map from image
pixels = img.load() # create the pixel map
## defining sum of average to sum average of each pixel
average_sum=0
# for every pixel
for i in range(img_width):
for j in range(img_height):
## finding average of pixels
avg=sum(pixels[i,j])/3
## adding average to average_sum
average_sum+=avg
## finding average brightness by dividing sum by width*height
avg_bright = average_sum/(img_width*img_height)
## finding factor x
x=128/avg_bright
# multiplying x with every pixel
for i in range(img_width):
for j in range(img_height):
## multiplying x with pixels, using list comprehension method to multiply each element by x
## then converting float to int and then converting generated list to tuple
pixels[i,j]=tuple([int(p*x) for p in pixels[i,j]])
return img

CODE IMAGE

INPUT IMAGE

OUTPUT IMAGES

a. Grey Scale

b. Black and White

c. Sepia

d. Brightness

Add a comment
Know the answer?
Add Answer to:
from PIL import Image import random # NOTE: Feel free to add in any constant values...
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 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...

  • 4. Write a function extract(pixels, rmin, rmax, cmin, cmax) that takes the 2-D list pixels contai...

    Please design the function in version 3 of python 4. Write a function extract(pixels, rmin, rmax, cmin, cmax) that takes the 2-D list pixels containing pixels for an image, and that creates and returns a new 2-D list that represents the portion of the original image that is specified by the other four parameters. The extracted portion of the image should consist of the pixels that fall in the intersection of the rows of pixels that begin with row rmin...

  • use MATLAB to upload the following: an image that you want to process (can be taken...

    use MATLAB to upload the following: an image that you want to process (can be taken yourself or downloaded from the internet) a script that processes the image in TWO ways. manipulates the colors averages pixels together Please make sure the script displays the images (like how I did with the 40 and 80 pixel averaging) so I can easily compare them to the original. Make sure to COMMENT your code as well. Homework 13 Please upload the following: an...

  • the picture above is the one you are supposed to use for the MATlab code please...

    the picture above is the one you are supposed to use for the MATlab code please help Problems. Grayscale images are composed of a 2D matrix of light intensities from O (Black) to 255 (White). In this lab you will be using grayscale images and do 2D-array operations along with loops and iflelse branches. 1. We can regard 2D grayscale images as 2D arrays. Now load the provided image of scientists at the Solvay Conference in 1927 using the imread)...

  • Image proccessing in PROGRAMING C NO MAIN FUNCTION NEEDED! Color-Filter an image: 1. All pixels in...

    Image proccessing in PROGRAMING C NO MAIN FUNCTION NEEDED! Color-Filter an image: 1. All pixels in the picture with color in the chosen range will be replaced with new color. The following shows the pseudo code for the color filter. if (R in the range of [target_r - threshold, target_r + threshold]) and (G in the range of [target_g - threshold, target_g + threshold]) and (B in the range of [target_b - threshold, target_b + threshold]) R = replace_r ;...

  • Hi. I require your wonderful help with figuring out this challenging code. import java.awt.Color; import java.awt.image.BufferedImage;...

    Hi. I require your wonderful help with figuring out this challenging code. import java.awt.Color; import java.awt.image.BufferedImage; import java.io.*; import javax.imageio.ImageIO; public class ImageLab { /* * This is the grayscale example. Use it for inspiration / help, but you dont * need to change it. * * Creates and returns a new BufferedImage of the same size as the input * image. The new image is the grayscale version of the input (red, green, and * blue components averaged together)....

  • The ACME Manufacturing Company has hired you to help automate their production assembly line. Cameras have...

    The ACME Manufacturing Company has hired you to help automate their production assembly line. Cameras have been placed above a conveyer belt to enables parts on the belt to be photographed and analyzed. You are to augment the system that has been put in place by writing C code to detect the number of parts on the belt, and the positions of each object. The process by which you will do this is called Connected Component Labeling (CCL). These positions...

  • In c++ The iron-puzzle.ppm image is a puzzle; it contains an image of something famous, howeve...

    In c++ The iron-puzzle.ppm image is a puzzle; it contains an image of something famous, however the image has been distorted. The famous object is in the red values, however the red values have all been divided by 10, so they are too small by a factor of 10. The blue and green values are all just meaningless random values ("noise") added to obscure the real image. If you were to create a grayscale image out of just the red...

  • 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...

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