9: Images and Arrays

What We Will Cover


Illuminations

Questions from last class or the Reading?

Homework Questions?

9.1: Midterm Preparation

Learner Outcomes

At the end of the lesson the student will be able to:

  • Describe the ground rules for the midterm exam
  • Start preparing for the midterm exam

9.1.1: About the Exam

Important Midterm Exam Information

Date: 4/18/12
Location: Regular Classroom
Start time:

Last Name Start Time
A-L 2:00 PM
M-Z 3:00 PM
  • Exam question types include multiple choice and short programming problems
  • You will have about 50 minutes to complete the exam

Ground Rules

  • You must attend the exam or you will receive a score of zero (0)
    • Except by prior arrangement with the instructor
  • I am using Blackboard to administer the test
  • Since there are more students than computers, we must take the exams in shifts
  • Shifts are determined by your last name as shown above
  • If you want to change shifts then you must discuss your situation with me
  • The exam is closed books and closed notes
    • However, you may have one 3" x 5" card of handwritten notes for the exam
  • You may use a computer from the classroom, but only to take the exam in Blackboard
  • You may have a sheet of blank scratch paper
  • You may use the computer to compile and run programs with Greenfoot
  • You may NOT use the computer to view documents on the Internet
  • You may NOT use a calculator or other electronic device
    • Thus, you may NOT use your own computer to take the exam
    • If you have a cell phone visible or in use during the exam, you will automatically fail
  • You may NOT communicate with anyone but the instructor during the exam

3"x5" Card Requirements

  • Put your name on your card
  • Maximum card or paper size is 3 inches by 5 inches
  • You may use both sides of the card
  • Notes must be handwritten and NOT photocopied
  • Notes cannot have any complete methods -- only code snippets
  • Any 3" x 5" cards violating these rules will be confiscated before the test
  • You must turn in your 3" x 5" card after the exam in any case

9.1.2: Test Preparation Self Assessment

Take two minutes to read and answer the following questions.

  1. How well did you do on the last midterm exam?

  2. Do you attend all classes and use effective note-taking strategies?

  3. Do you review your reading and lecture notes the day after and on a weekly basis?

  4. Do you analyze your homework, quizzes, and exams throughout the semester for pattern and error?

  5. Do you identify possible exam questions while reading and taking notes?

  6. Do you study with a partner or a group?

  7. Do you use your instructors' office hours to ask questions about material you don't understand?

  8. Do you use study strategies appropriate for the type of exam (like flashcards to memorize facts, completion of example problems to understand processes)?

  9. Do you use small portions of time for review rather than cramming?

  10. Do you learn course material in-depth enough that you could explain it to one of your classmates?

Discussions Questions

  • What did you do to prepare for the last midterm exam?
  • What part of your preparation was successful and what should you change?
  • How much time do you plan to dedicate to test preparation?
  • What do you plan to do to prepare for this exam?

9.1.3: How to Study for the Exam

forked road
  • No one can ace a test without studying and understanding the material
  • To get an "A" you need to thoroughly prepare for the test well in advance
  • With the midterm approaching, you have a choice:
    • Study and do well, or
    • Not study and do less than your best
  • Remember that victims are people who let their lives control them, like a pawn on a chessboard
  • Creators are people who controls their own life, like a person playing chess
  • You can take responsibility for studying and do well on a test
  • Or you can make excuses and do less than you are capable of on a test

Boosting Your Performance

Here are some steps you can take to improve your test results:

  1. Compile a list of topics you might be tested on.

    Look over your assignments, exercises, and lecture notes to determine what you covered. Write a list of topics from these sources.

  2. Make sure you understand all the topics on your list.

    Correct any mistakes you may have made in your assignments or exercises.

  3. Identify the most probable exam topics for thorough study.

    To do well, you need deep understanding of the test topics. Oftentimes, you can tell what is on a test simply by which topics the instructor spends the most time talking about.

  4. Create a list of test questions.

    Turn headings from the textbook and lecture notes into questions. Look at the section summaries in the lectures and read the Check Yourself questions.

  5. Study your questions over and over until you know them perfectly.

    Make flash cards with questions on one side and answers on the other. Carry the cards with you and review them when you have a few minutes available. Have other people ask you questions from your flash cards.

  6. Prepare your 3"x5" card of test notes.

    Since the instructor allows a 3"x5" card, make use of it. For the topics you had the most trouble with, write down a short note or summary. If the pressure of the test causes you to forget something, you can refer to your card.

More Information

9.1.4: Exam Topics

  • To help you prepare for the exam, I am providing a list of exam topics
  • In return, I want each student to pick one topic and prepare 5 Jeopardy-style questions for their topic
  • Also, develop a short Jeopardy-style category name
  • At the next class meeting we will review the questions to help us prepare for the midterm

Exam Topics

  1. Boolean variables (5.2.1)
  2. Logical operators (5.2.2)
  3. Abstraction (5.2.3)
  4. Loops and counting (5.3.3)
  5. Arrays (5.3.5)
  6. Constants (6.1.4)
  7. Color (6.2.1)
  8. Drawing Shapes (6.2.3)
  9. Abstract classes (7.1.1 and Exercise 7.1)
  10. Floating-Point Numbers (7.1.3)
  11. Overloading (7.1.4)
  12. this and this() (7.1.5)
  13. Algorithms, psuedocode and method stubs (7.2.1 and 7.2.2)
  14. Lists and the enhanced for loop (7.2.3 and 7.2.4)
  15. Timing over multiple game cycles (8.1.4 and 8.2.5)
  16. Casting and superclass types (8.1.6)
  17. Reference types (8.2.2)
  18. static types and methods (8.2.2)
  19. Caching (8.2.2)
  20. Drawing text and fonts (8.3.3)
  21. Declaring an Array (9.2.3)

Exercise 9.1

Take a minute to review the above topics and select one of them to prepare 5 potential test questions.

As a homework for the next class meeting, prepare a list of 5 Jeopardy-style questions/answers on your topic. Jeapordy-style questions/answers have a twist. You provide the answer and the player states the question. For example, an answer is, "In the Java Programming language, this variable type only has a value of either true or false." The player would pose the question as, "What is boolean?"

Bring a paper copy of your study questions/answers and also post them in the Discussions area of Blackboard. For each answer, supply a question and a point value of 100, 200, 300, 400 or 500. Questions should be in the form of, "What is ... ?"

9.2: Digital Images and Pictures

Learner Outcomes

At the end of the lesson the student will be able to:

  • Choose the best type of image files for a scenario
  • Describe the composition of a digital image
  • Construct an array of pixels
  • Access elements of a pixel array
  • Run the Picture World scenario

9.2.1: About Digital Images

  • Today we discuss a key part of games: images (or pictures)
  • We will learn how digital images work and how to manipulate (change) them

Images and File Formats

  • Digital images are stored in computer files
  • Several different standards exists for encoding the image files
  • Greenfoot supports the image formats: JPEG, PNG, GIF, BMP and TIFF
  • Some of the formats use compression to reduce the file size
  • Compression means that you make the file sizes smaller
  • The JPEG format compresses large images very well but does not support transparency
  • The PNG format handles transparency but has less compression than JPEG
  • These file formats can be loaded and manipulated by image editing programs
  • We can see some of these editing programs listed below

Some Image Editing Programs

Check Yourself

  1. True or false: an image file format is the particular way that image information is encoded for storage in a computer file.
  2. Of these image file formats, ________ is NOT supported by Greenfoot:
    1. BMP
    2. GIF
    3. PNG
    4. PPM
  3. Image ________ makes image file size smaller.

9.2.2: Arrangement of Images

  • Digital images are composed of pixels (picture elements)
  • A pixel is a dot on the computer screen
  • Each pixels has a red, green and blue component as shown in the following close up of a laptop screen (from Wikipedia)

    Close up of pixels

  • As we can see, each pixel of this laptop screen has red, green and blue sub-elements
  • Each pixel has a value for the amount of red, green and blue (RGB) to display
  • Remember from lesson 6.2.1 that we combine RGB values to produce different colors

    RGB colors

Processing Pixels

  • Images have lots of pixels
  • For example, a 640 x 480 picture has 307,200 pixels
  • Declaring variables for all the pixels would be tedious and awkward
    pixel1, pixel2, pixel3, pixel4, pixel5, ...
  • What is a better way to work with lots of data that is all of the same type? Click to show answer

Check Yourself

  1. True or false: a picture is composed of a large number of pixels.
  2. A pixel has three color values: R__________, G__________, B__________.
  3. To work with lots of data that is all of one type, we can use a(n) ________.

9.2.3: Arrays of Pixels

  • Recall from lesson 5.3.5 that an array is a list of data
  • Images are stored in a computer's memory as an array of pixels
  • Arrays are arranged as a sequence of elements (see below)
  • Each element has an index number assigned to it
  • The first element is at index 0, the second at index 1, the third at index 2, and so on
  • Arrays know their length from a public length field, like:
    int numElements = arrayObj.length;

First Five Elements of an Array of Pixels

array of pixels

Declaring an Array

  • In lesson 5.3.5 we declared and assigned values to an array like:
    private String[] whiteKeys = { "a", "s", "d", "f", "g",
        "h", "j", "k", "l", ";", "'", "\\" };
    
  • This is known as static initialization because the array is created and assigned values by the compiler
  • Another way to declare an array is with dynamic initialization
  • The general syntax for declaring an array is:
    dataType[] arrayName;
    or
    dataType arrayName[];
    
  • Where:
    • dataType: the data type of all the array items
    • arrayName: the name you make up for the array
  • For example, to declare an array named pixels of type Pixel:
    Pixel[] pixels;
  • The syntax to allocate memory space for an array:
    arrayName = new dataType[size];
    
  • Where:
    • arrayName: the name of the array
    • dataType: the data type of all the array items
    • size: the number of data items the array can hold
  • For example, to allocate memory for 5 pixels:
    pixels = new Pixel[5]
  • You can combine the declaration and allocation in one statement
  • For example:
    Pixel[] pixels = new Pixel[5];
    
  • This is like declaring 5 variables of type Pixel numbered as:
    pixels[0], pixels[1], pixels[2], pixels[3], pixels[4]

Check Yourself

  1. True or false: an array is a list of data, of which all the elements can be of different types.
  2. The last element of an array of 307,200 pixels has an index number of ________.
  3. Write the code to declare an array of type int named score and allocate 42 elements for the array..

    answer

9.2.4: Accessing Array Elements

  • Once we have an array, we can access its individual elements using an index
  • For example, we can assign an element to a different variable:
    Pixel pix = pixels[3];
  • Also, we can assign a new value to an array element, like:
    pixels[4] = pix;
  • We can work with array elements like any other variable
  • The only difference is we must include the square brackets and index number of the particular element

Accessing Array Elements with Loops

  • Remember from lesson 5.3.6 that we can use loops access array elements
  • For example, if we have an array of scores like:
    int[] scores = new int[5];
    scores[0] = 100;
    scores[1] = 99;
    scores[2] = 90;
    scores[3] = 95;
    scores[4] = 87;
    
  • We can use a loop to print all the score values to the terminal window:
    for (int i = 0; i < scores.length; i++)
    {
        System.out.println(scores[i]);
    }
    

Array Index Out of Bounds

  • A common error is using a nonexistent index
  • For an array of length 5, the indexes are 0 through 4
  • An index beyond this is "out of bounds"
  • Using an out of bounds index value produces an error message!
    ArrayIndexOutOfBoundsException
  • For example, the following code will produce such an error
    int[] scores = new int[5];
    scores[5] = 100;
    
  • Trying to use an index less than 0 or more than length - 1 causes the error:
    ArrayIndexOutOfBoundsException

Check Yourself

  1. Write a statement to assign array element 2 of an array named scores to a new variable named myScore.

    answer

  2. True or false: the following code is legal for the array declared in the previous question.
    scores[2] = scores[2] + 1;
  3. What is wrong with the following code, if anything, for the array declared in question 1? (answer)
    for (int i = 0; i <= scores.length; i++)
    {
        System.out.println(scores[i]);
    }
    

9.2.5: The Picture World Scenario

  • Let us look at a scenario for manipulating images
  • The scenario was written by Cay Horstmann and Barbara Ericson
  • Lets download and install the scenario:

    Scenario file: PictureWorld.zip.

  • Save the file inside the Greenfoot scenarios folder.
  • Start Greenfoot and open the scenario (Greenfoot unzips the file for us)

How the Scenario Works

  • The scenario starts by creating and displaying a MyPicture object
  • The scenario operates by right-clicking the picture and selecting a method
  • For instance, we can select a different picture by choosing the pick() method inherited from Picture
  • By choosing the decreaseRed() method, we can reduce the amount of red in every pixel by 50%

Greenfoot Controls

  • We can reset the image to its original form by pressing the Reset button
  • Pressing the Act button executes the act() method one time
  • The act() method contains a call to decreaseRed()
  • What happens if we press the Run button?
  • As we can see, the Run button is not that useful in this scenario
  • However, you might use Run if you want to call a method repeatedly

Check Yourself

  1. To choose a different image to display, select the ________ method.
  2. To remove 50% of the red in every pixel, select the ________ method.
  3. True or false: to get the most out of the scenario, press the Run button.

Exercise 9.2

In this exercise, we do explore the Picture World scenario.

Specifications

  1. Download the following file and save it in the scenario folder of Greenfoot.

    Scenario file: PictureWorld.zip.

  2. Start Greenfoot and open the scenario.

    Greenfoot unzips the file for us.

  3. Right-click the image, select the act() method and observe the behavior.

    You should see the amount of red decrease in the image. If you have problems, ask a classmate or the instructor for help as needed.

  4. Press the Greenfoot control button labeled Reset.

    You should see the image return to its original form. If you have problems, ask a classmate or the instructor for help as needed.

  5. Experiment with the various of methods of MyPicture to see what is available.
  6. Look at the code for decreaseRed() to see how it works.
  7. There is nothing to turn in for this exercise.

As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 9.2.6: Review.

9.2.6: Review

Answer these questions to check your understanding. You can find more information by following the links after the question.

  1. True or false: an image file format is the particular way that image information is encoded for storage in a computer file. (9.2.1)
  2. Which of these image file formats are supported by Greenfoot: (9.2.1)
    1. BMP
    2. GIF
    3. PNG
    4. PPM
  3. Image compression makes image files ____________. (9.2.1)
  4. True or false: a picture is composed of a large number of pixels. (9.2.2)
  5. A pixel has three color values: __________, __________, __________. (9.2.2)
  6. To work with lots of data that is all of one type, we can use a(n) ___________. (9.2.2)
  7. True or false: an array is a list of data of various types. (9.2.3)
  8. The last element of an array of 42 pixels has an index number of __________. (9.2.3)
  9. Write the code to declare an array of type int named scores and allocate 42 elements for the array. (9.2.3)
  10. Write a statement to assign element 2 of an int array named scores to a new variable named myScore. (9.2.4)
  11. Is the following code legal for the array declared above? (9.2.4)
    score[10] = score[10] + 1;
  12. What is wrong with the following code, if anything, for the array declared above? (9.2.4)
    for (int i = 0; i <= scores.length; i++)
    {
        System.out.println(scores[i]);
    }
    
  13. True or false: the Picture World scenario allows you to manipulate pictures. (9.2.5)

9.3: Manipulating Images

Learner Outcomes

At the end of the lesson the student will be able to:

  • Manipulate digital images
  • Get information from a picture object
  • Set information into a picture object

9.3.1: About Manipulating Images

  • To manipulate images we need to manipulate the pixels that make up the image
  • Usually, we change the red, green or blue values of the pixel
  • Most of the code to work with images is contained in the Picture and Pixel classes
  • Let us look at the Picture class first

Looking at Picture Data

  • A Picture object has data that it reads from an image file
  • If we look at the documentation, we see that Picture has methods to access the data
  • For instance, we can get the width and height of an image: getWidth() and getHeight()
  • Also, we can get an array of Pixel objects: getPixels()
  • Looking at the documentation we can see other methods of interest we may use later

Looking at Pixel

  • Pixel is a class with data variables and methods
  • Each Pixel object stores it is within and its location in the picture
  • We can get the x and y location of the pixel by calling: getX() and getY()
  • Also, The Pixel class has methods to get and set its red, green and blue values
  • Each RGB value must be between 0 (minimum) and 255 (maximum)
  • In addition, we can get and set all three RGB values at once using: getColor() and setColor()

Check Yourself

  1. True or false: manipulating an image means you manipulate the pixels that make up the image.
  2. True or false: to manipulate a pixel you changes its red, green or blue values.
  3. The method to retrieve an array of pixels from Picture is named ________.

9.3.2: Reviewing Colors

  • Remember from lesson 6.2.1 that colors are made up of red, green and blue values
  • Java Supports the standard RGB color model using the Color class
  • You create colors by specifying red, green and blue (RGB) values
  • RGB values are specified using int values from 0 to 255:
    Color(int r, int g, int b)  // 0 - 255
    
  • For example:
    Color chocolate = new Color(204, 102, 0);
    
  • In addition, the Color class has several static color constants that you can use in place of numbers as shown below
  • Notice that the Picture World scenario has a Color class as well
  • The Color class is a subclass of java.awt.Color that allows you to create colors using double values

Class Color of PictureWorld

public class Color extends java.awt.Color
{
    public Color(double red, double green, double blue)
    {
        super((int) red, (int) green, (int) blue);
    }

    public Color(java.awt.Color color)
    {
        super(color.getRGB());
    }
// color constant code ommitted
}

Some Color Constants

Color Constant Red, Green, Blue
Color.RED 255, 0, 0
Color.BLUE 0, 0, 255
Color.YELLOW 255, 255, 0
Color.BLACK 0, 0, 0
Color.PINK 255, 175, 175
Color Constant Red, Green, Blue
Color.GREEN 0, 255, 0
Color.MAGENTA 255, 0, 255
Color.CYAN 0, 255, 255
Color.WHITE 255, 255, 255
Color.GRAY 128, 128, 128

Check Yourself

  1. True or false: class Color of the PictureWorld scenario was included to allow RGB values to be created using type double in the range of 0-255.
  2. Write the code to construct the following colors in Java:
    Color red =   ; answer
    Color green = ; answer
    Color blue =  ; answer
    Color pink =  ; answer
    
  3. What are two ways to complete the following statement? (answer)
    Color magenta = 

9.3.3: Manipulating Pixel Color Values

  • We can work with colors
  • Now let us work directly with the colors of a pixel

Getting Pixel Colors

  • We can get the Color object from a pixel and then get the values from the Color object:
    Color color = pixelObj.getColor();
    int red = color.getRed();
    int green = color.getGreen();
    int blue = color.getBlue();
    
  • Another way is to get the value directly from the Pixel object:
    int red = pixelObj.getRed();
    int green = pixelObj.getGreen();
    int blue = pixelObj.getBlue();
    

Changing Pixel Colors

  • To change a pixel color, we can set RGB values individually:
    pixelObj.setRed(value),
    pixelObj.setGreen(value),
    pixelObj.setBlue(value),
    
  • Another way is to construct a Color object and set the color:
    pixelObj.setColor(colorObj)
    
  • However, we must call repaint() to see the change in the picture
    pictureObj.repaint();

Example: Changing the Red in a Picture

  • One way to change a picture is to reduce the amount of red in it
  • As an example, if we have a value of 200 and we want to decrease the red by half, what is the new value?
  • What code do we write to reduce the value by half? Click to show answer
  • If we have a red value of 100 and want to increase it by 50%, what is the new red value?

Check Yourself

  1. To get the red value from a pixel object call the method ________.
  2. To set the red value of a pixel object, call the method ________.
  3. True or false: To see a change in color, you must call the repaint() method of Picture.
  4. Enter the code to increase the blue value of pixelObj by 50%.

    answer

9.3.4: Using Loops with Pixel Arrays

  • There are 152,100 (450 x 338) pixels in the rose image

    A rose by any other name

  • Do we really want to write the code to change each one of these pixels?
    1. Get the current pixel
    2. Get the red value of the current pixel
    3. Change the red value of the current pixel to half the original value (value / 2)
    4. Put the new red value in the current pixel
    5. Repeat 152,099 times
  • The solution to our problem is to use a loop

Using Loops with Arrays

  • We have used loops with list of data previously, including:
  • We can apply the same techniques to manipulate arrays of pixels
  • For example, look at the decreaseRed() method from MyPicture shown below
  • Here we see an example of using the enhanced for loop we discussed in lesson 7.2.4

Method decreaseRed() of MyPicture

public void decreaseRed()
{
    double red = 0;

    for (Pixel pix : getPixels())
    {
        red = pix.getRed();
        red = red * 0.5;
        pix.setRed(red);
    }
}

Organizing with Methods

  • In MyPicture, notice how the various image manipulation procedures are organized into methods
  • Organizing using methods makes the code easier to write and maintain
  • Also, in this scenario especially, we need methods to access the image manipulation techniques

Check Yourself

  1. The number of pixels in a picture that measures 355 x 400 is ________.
  2. To change the value of every pixel in an image, use a ________.
  3. To find out how many elements are in an array, use the ________ array variable.

Exercise 9.3

In this exercise, we write methods to manipulate pictures.

Specifications

  1. Start Greenfoot and open the Picture World scenario from the last exercise.

    Scenario file: PictureWorld.zip.

  2. Open the MyPicture class and write a method named increaseRed() that loops through all the pixels in an image and doubles the red values.

    Hint: you will need to use an if-statement to prevent the red value from exceeding 255.

    When you are finished, compile and run the scenario to verify your method works. If you have problems, ask a classmate or the instructor for help as needed.

  3. Write a second method named zeroBlue() that sets all the blue values to 0.

    When you are finished, compile and run the scenario to verify your method works. If you have problems, ask a classmate or the instructor for help as needed.

  4. Write another method named allBlue() that keeps only the blue values (sets all red and green values to 0).

    When you are finished, compile and run the scenario to verify your method works. If you have problems, ask a classmate or the instructor for help as needed.

  5. Save a copy of your scenario as we will be adding to it in a future exercise.

    Only submit the final scenario with all the lesson exercises completed, not the intermediate scenarios.

As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 9.3.5: Review.

9.3.5: Review

Answer these questions to check your understanding. You can find more information by following the links after the question.

  1. True or false: manipulating an image means you manipulate the pixels that make up the image. (9.3.1)
  2. True or false: to manipulate a pixel you changes its red, green or blue values. (9.3.1)
  3. The method to retrieve an array of pixels from Picture is __________________. (9.3.1)
  4. Write the code to construct the following colors in Java: (9.3.2)
    Color red =
    Color green =
    Color blue =
    Color pink =
    
  5. What are two ways to complete the following statement? (9.3.2)
    Color magenta =
  6. What are two ways to get the red value from a pixel? (9.3.3)
  7. What are two ways to set the red value of a pixel? (9.3.3)
  8. True or false: To see a change in color, you must call the repaint() method of Picture. (9.3.3)
  9. Write code statement(s) to increase the blue value of pixelObj by 50%. (9.3.3)
  10. How many pixels are in a picture that measures 200 x 300? (9.3.3)
  11. To change the value of every pixel in an image, use a _________. (9.3.3)
  12. To find out how many elements are in an array, use the ___________ array variable. (9.3.3)

9.4: Reviewing for the Exam

Learner Outcomes

At the end of the lesson the student will be able to:

  • Review possible exam questions

9.4.1: Reviewing the Topics

  • Remember that we each chose a test topics in Exercise 9.1
  • Your homework, due today, was to develop at least 5 Jeopardy-style questions from your selected topic
  • Break into groups and choose one topic and set of 5 questions
  • Write the topic and 5 questions on the board

Test Review Exercise

  • Each group picks a category and amount ($100-500)
    • Do not pick a category that a member of your group wrote
  • As a group, answer the question
  • Review your answer with the class

9.4.2: More Test Preparation

  • To help you study I am providing some practice test problems: Midterm 2 Practice Problems
  • The questions are intended to help you get more practice for the code writing problems
  • These questions, along with the questions posted in the discussion group, are to help you study for the midterm
  • The questions are NOT intended to tell you everything that is on the exam

Wrap Up

Due Next:
A7: Asteroids Deluxe (4/4/12)
Midterm Exam #2 (4/18/12)
A8: Image Manipulation (4/25/12)
  • When class is over, please shut down your computer
  • You may complete unfinished lesson exercises at any time before the due date.
Home | Blackboard | Schedule | Syllabus | Room Policies
Help | FAQ's | HowTo's | Links
Last Updated: April 11 2012 @00:12:39