Question

#PYTHON#

In this exercise you will write code which loads a collection of images (which are all the same size), computes a pixelwise average of the images, and displays the resulting average.

The images below give some examples that were generated by averaging "100 unique commemorative photographs culled from the internet" by Jason Salavon. Your program will do something similar.

Write a function in the cell below that loads in one of the sets of images and computes their average. You can use the os.listdir to get the list of files in the directory. As you load in the images, you should compute an average image on the fly. Color images are represented by a 3-dimensional array of size (HxWx3) where the third dimension indexes the red, green and blue channels. You will want to compute a running average of the red, green and blue slices in order to get your final average color image.

You should encapsulate your code in a function called average_imagethat takes the image directory as an input and returns the average of the images in that directory. Your function should implement some error checking. Specifically your function should skip over any files in the directory that are not images (plt.imread will thrown an OSError if the file is not an image). It should ignore images that are not color images. Finally, it should also skip any images which are not the same height and width as the first color image you load in.

In[]: # # these are the only modules needed for problem #2 import numpy as np import os import matplotlib.pyplot as plt In [: def average_image (dirname): Computes the average of all color images in a specified directory an The function ignores any images that are not color images and ignore the same size as the first color image you load in Parameters dirname: str Directory to search for images Returns numpy.array (dtype-float) HxWx3 array containing the average of the images found #[your code here] for file in os.listdir(dirname) filenameos.path.join(dirname,file) if os.path.isfile(filename): #[your code here] return Iaverage [2.2] Write code below which calls your average image0 function twice, once for each set of images Display the resulting average images. Also display a single example image from each set for comparison

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

The required code is as follows:

import numpy
import os
import matplotlib as plt

def average_image(dirname):
   images = []
   i = 0

   # Reading files
   for file in os.listdir(dirname):
       filename = os.path.join(dirname, file)
       if os.path.isfile(filename):
           img = imread(filename)
          
           # For OSError checking
           if (! img):
               continue   # Ignore that item and continue scanning other images.
          
           # Type checking; Suppose size of all images are same as red-pixels, green-pixels, and blue-pixels as CONSTANTS.
           elif (!(img[0]==red-pixels && img[1]==green-pixels && img[2]==blue-pixels)):
               continue # Ignore that item and continue scanning other images.

   else:       
               plt.imshow(img)

               images[i] = img

   size = len(images)  
  
   # Assuming that all sublists have same length, we've checked about it also.
   num_red = len(images[0])
   num_green = len(images[0][1])
   num_blue = len(images[0][2])

   sum_red = 0
   sum_blue = 0
   sum_green = 0

   for a in range size:
       sum_red += images[a][0]
       sum_green += images[a][1]
       sum_blue += images[a][2]

   Iaverage = np.array(sum_red, sum_green, sum_blue)
   return Iaverage

Add a comment
Know the answer?
Add Answer to:
#PYTHON# In this exercise you will write code which loads a collection of images (which are...
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
  • % BACKGROUND:Image processing is the generation of a new image from one or more existing images....

    % BACKGROUND:Image processing is the generation of a new image from one or more existing images. % MATLAB makes it easy to work with images by providing some basic functions % that allow you to read and write images in standard image -file formats, such as JPEG % Locate the attached photo of a blue bird stored in JPEG format, bbird.jpg (must be on same folder as script). % Fill in the ? in the code with correct values to...

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

  • C Language Write the code that dynamically allocates an array of struct objects based on a...

    C Language Write the code that dynamically allocates an array of struct objects based on a size entered through the command line arguments, You will use the following struct and enum. typedef enum Color { RED, GREEN, BLUE } Color; typedef struct MyStruct { int value; Color color; } MyStruct; Write the code to do the following: a. Check for one additional command line argument. Only proceed to the rest of the program if it exists and that the value...

  • C++, you can skip #1 Part 2. Practice Problems The following questions ask you to write...

    C++, you can skip #1 Part 2. Practice Problems The following questions ask you to write a program to compute the area of a circle using the equation A = 1 m2. The radius of the circle should be entered by the program user. 1. Draw a structure chart 2. Make a new directory called CircleFun and make it the CWD. Work inside this directory to keep your files (Main.cpp, Circle.cpp, Circle.h) grouped together 3. Using the three-file format a....

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

  • Image processing Matlab problem. Could you please help me to write a Matlab code to read...

    Image processing Matlab problem. Could you please help me to write a Matlab code to read images, equalize contrasts, covert images to grayscale and binary, then display on same windows. Then perform SOBEL and CANNY edge detection on images. Final make MATLAB to count the number of circles in images (circles and red circles) And how can we distinguish circles by color? and how to count number of red, green and blue circles separately for example.

  • Can you write a Python 2.7 function that takes a directory path, and prints the size,...

    Can you write a Python 2.7 function that takes a directory path, and prints the size, in bytes, of all the files, ignoring sub-directories, reverse sorted by size, with the total in the following exact format: file_name_2: 200000 file_name_1: 100000 file_name_3: 1000 > 3 File(s) - Total: 301000. Provide the copyable code.

  • Java program that creates a photo album application.    Which will load a collection of images...

    Java program that creates a photo album application.    Which will load a collection of images and displays them in a album layout. The program will allow the user to tag images with metadata: •Title for the photo .      Limited to 100 characters. •Description for the photo . Limited to 300 characters. •Date taken •Place taken Functional Specs 1.Your album should be able to display the pictures sorted by Title, Date, and Place. 2.When the user clicks on a photo,...

  • Image histogram code in python?

    In this exercise you should write a Python function that computes the histogram of an intensity (gray scale) image. Do not use specifific Python functions for histogram computation (like hist or imhist). Create a new function my_hist and start with the following lines: function [h] = my_hist(im) % H = MY_HIST(IM) computes the histogram for the intensity % image IM (with values from 0 to 255) and returns a vector H % with 256 dimensions % get the image size:...

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

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