750 likes | 920 Views
Manipulating Pictures, Arrays, and Loops. Barb Ericson Georgia Institute of Technology June 2005. Learning Goals. Understand at a conceptual and practical level How to manipulate digital images using methods? What is an array? What is a loop? While and for loops What is a package?
E N D
Manipulating Pictures, Arrays, and Loops Barb Ericson Georgia Institute of Technology June 2005 Georgia Institute of Technology
Learning Goals • Understand at a conceptual and practical level • How to manipulate digital images using methods? • What is an array? • What is a loop? • While and for loops • What is a package? • How do you import classes? • What is a comment? Georgia Institute of Technology
Digital Pictures • Represented as an array of pixels • With a red, green, and blue value stored for each pixel • Stored in .jpg (JPEG) files • International standard • With lossy compression • Lossy means not all data is stored • But what is lost isn’t that important • Compression means made smaller • Other formats for storing digital pictures are GIFF and BMP Georgia Institute of Technology
Pictures have lots of Pixels • How can we refer to each pixel? • pixel1, pixel2, pixel3, pixel4, pixel5, … • Do we really want to name each one? • There are 640 x 480 = 307,200 pixels • How do we deal with lots of data of the same type? • Use an array Georgia Institute of Technology
What is an Array? • Storage for a sequence of items • Of the same type • You can access items by using an index • The index starts at 0 • The first item is at index 0 • The last item is at index (length – 1) • Arrays know their length (have a public length field) • arrayObj.length 0 1 2 3 4 5 3 7 9 2 1 5 0 1 2 3 8 3 2 6 Georgia Institute of Technology
Manipulating a Picture • To manipulate a picture we need to manipulate the pixels that make up the picture • Change the red, green, or blue values at the pixel • Pixel is a class that we created • Each pixel object has a red, green, and blue value Georgia Institute of Technology
What Data does a Picture Object Have? • A picture object has an array of pixel objects • That it read from the JPEG file • It knows it’s width pictureObj.getWidth() • It knows it’s height pictureObj.getHeight() • It knows how to return an array of pixels Pixel[] pixelArray = pictureObj.getPixels() Georgia Institute of Technology
Picture Exercise • Create a picture in DrJava • get the pictures width, height, and pixels String fileName = FileChooser.pickAFile(); Picture pictureObj = new Picture(fileName); int width = pictureObj.getWidth(); System.out.println(“The picture width is “ + width); int height = pictureObj.getHeight(); System.out.println(“The picture height is “ + height); Pixel[] pixelArray = pictureObj.getPixels(); System.out.println(pixelArray.length + “ pixels”); Georgia Institute of Technology
Pixel Objects • Each pixel has a red, green, and blue value • getRed(), getGreen(), getBlue() • setRed(v), setGreen(v), setBlue(v) • Each pixel knows the location it was in the picture object • getX(), get(Y) • You can also get and set the color at the pixel • getColor(), setColor(color) Georgia Institute of Technology
Color Objects • There is a class defined in Java that represents color • The Color class in the package java.awt • To use the class you must either • import java.awt.Color; • Use the full name java.awt.Color • You can create a color object by giving the red, green, and blue values • Color colorObj = new Color(255,10,125); Georgia Institute of Technology
Predefined Colors • The Color class has defined class constants for many colors • Color.red, Color.green, Color.blue, Color.black, Color.white, Color.yellow, Color.gray, Color.orange, Color.pink, Color.cyan, Color.magenta • Or you can use all uppercase names • Color.RED, Color.BLUE, Color.BLACK, … Georgia Institute of Technology
Getting and Setting Pixel Colors • To get a pixel’s color as a color object • Color color1 = pixelObj.getColor(); • int red = color1.getRed(); • int green = color1.getGreen(); • To set a pixel’s color using a new color object • Color color2 = new Color(red,green,blue); • pixelObj.setColor(color2); Georgia Institute of Technology
Using Classes in Packages • All classes in the Java language are in packages • You can use any class in java.lang • System, Math, Object • For classes in other packages you need to import them • import java.awt.Color; • Import java.awt.*; //import all classes in this package • To use the short name: Color • Or use the fully qualified name • packageName.ClassName • java.awt.Color Georgia Institute of Technology
Undefined Class Error • If you forget to import a class • Yet, you use the short name for the class • It won’t compile • Undefined class error • Undefined class errors mean • You need to import the class • Or you misspelled the class • Or used the wrong case Georgia Institute of Technology
Pixel Exercise • In DrJava • Pick a file and create a picture object • Get the array of pixels from the picture object • Get the 1st pixel from the array of pixels • pixelObj = pixelArray[0]; • Get the red, green, and blue value for this pixel • Get the x and y location of this pixel • Get the color of this pixel • Get the red, green, and blue values of the color Georgia Institute of Technology
Changing Pixel Colors • There are two ways to change the color of a pixel in a picture • Set the red, green, and blue values individually • pixelObj.setRed(value), • pixelObj.setGreen(value), • pixelObj.setBlue(value), • Or set the color • pixelObj.setColor(colorObj) • But, you won’t see any change in the picture • Until you ask it to repaint: pictureObj.repaint(); Georgia Institute of Technology
Changing a Color • The Color class has methods for making a color object • Lighter • colorObj.brighter(); • Darker • colorObj.darker(); • Example > Color testColor = new Color(168,131,105); > System.out.println(testColor); java.awt.Color[r=168,g=131,b=105] > testColor = testColor.darker(); > System.out.println(testColor); java.awt.Color[r=117,g=91,b=73] > testColor = testColor.brighter(); > System.out.println(testColor); java.awt.Color[r=167,g=130,b=104] Georgia Institute of Technology
Rounding Errors • Notice that when you made the color darker and then lighter the resulting color was slightly off of the original • The change is calculated in floating point • The result is stored in integer form • The decimal part is lost • Rounding errors also occur because of the limited storage for floating point numbers • We can’t store all the digits in some numbers Georgia Institute of Technology
Pictures are 2-D Arrays • They have columns and rows (x and y) • You can get a pixel at a particular x and y location • Pixel pixelObj = picture.getPixel(x,y); • The columns and rows • start with index 0 • end with num -1 X Y Georgia Institute of Technology
Changing a Picture Exercise > String fileName = "C:/intro-prog-java/mediasources/caterpillar.jpg"; > Picture pictureObj = new Picture(fileName); > pictureObj.show(); > pictureObj.getPixel(10,100).setColor(Color.black); > pictureObj.getPixel(11,100).setColor(Color.black); > pictureObj.getPixel(12,100).setColor(Color.black); > pictureObj.getPixel(13,100).setColor(Color.black); > pictureObj.getPixel(14,100).setColor(Color.black); > pictureObj.getPixel(15,100).setColor(Color.black); > pictureObj.getPixel(16,100).setColor(Color.black); > pictureObj.getPixel(17,100).setColor(Color.black); > pictureObj.getPixel(18,100).setColor(Color.black); > pictureObj.getPixel(19,100).setColor(Color.black); > pictureObj.repaint(); Georgia Institute of Technology
How do we Know if it Worked? • A very important part of programming is testing the result • Just because code compiles and runs without error doesn’t mean it is correct • There could be an error in the logic • It could fail under certain conditions • It could even return the correct answer but for the wrong reason Georgia Institute of Technology
The Picture Explorer • Tool that creates a copy of the current picture and lets you explore it • See the color, x, and y values at the cursor • To use the tool on a picture object • pictureObj.explore(); • Use it to see if the colors have changed Georgia Institute of Technology
Changing the Red in a Picture • One way to change a picture is to reduce the amount of red in it • What if we want to decrease it by half? • If we have a value of 200 what should the new value be? • How do we reduce any value by half? • What if we want to increase it by 25%? • If we have a value of 100 what should the new value be? • How do we increase any value by 25%? Georgia Institute of Technology
Changing all the Pixels in a Picture • There are 329 * 150 = 49,350 pixels in the caterpillar picture • Do we really want to write the code to change each one of these? • Get the current pixel • Get the red value of the current pixel • Change the red value of the current pixel to 0.5 the original value • Put the new red value in the current pixel Georgia Institute of Technology
We Need a Loop (Iteration) • A way to execute a series of statements • With something changing each time the statements are executed • Different index of the pixel to change • And some way to tell when we are done with the repetition • Some test to see if the loop should stop Georgia Institute of Technology
Loop Exercise • Ask a person to clap 12 times • How does s/he know when to stop? • What changes each time s/he claps? • If you are following a recipe that asks you to stir the ingredients 50 times how would you do this? • What if you were trying to break a sit-up record • How would you know if you did break it? Georgia Institute of Technology
Loops often need Counters • If you want to do something x times you often need a counter • That starts at 0 • And you add 1 to it each time you finish doing the thing you are repeating • When the counter reaches the number you are trying to do you stop the loop • What is the value of the counter the last time the statements of the loop are executed? Georgia Institute of Technology
While Loops • In Java one way to repeat a block of statements while an expression is true is to use a while loop • Create a counter and set it to the start value • Check that the counter is less then the stop value • If it is less than execute the statements in the loop • Add one to the counter and go back to check that the counter is less than the stop value Georgia Institute of Technology
Total the Numbers from 1 to 100 • What if you want to add all the numbers from 1 to 100? • You will need something to hold the total • What type should it be? • What value should it start out with? • You will need something that counts from 1 to 100 • And add that value to the total • Stop when you get to 100 • What type should it be? What value should it start with? Georgia Institute of Technology
While Loop Syntax • Adding up the numbers from 1 to 100 int counter = 1; int total = 0; while (counter <= 100) { total = total + counter; counter = counter + 1; } System.out.println(total); Georgia Institute of Technology
Decrease Red Algorithm • To decrease the red value in a picture by 50% • Get the array of pixels from the picture • Set up an index to start at 0 • Check if the index is less than the length of the array • If it is go on to step 4 of the loop • If it isn’t jump to the first instruction after the loop • Get the pixel at the current index from the array of pixels • Get the red value at the pixel • Multiply the red value by 0.5 • Set the red value at the pixel to the reduced red value • Increment the index and go back to step 3 Georgia Institute of Technology
What is an Algorithm? • An algorithm is a description of the steps needed to do a task • Can be written in English • A recipe is an algorithm • A program is an implementation of an algorithm • in a particular computer language Georgia Institute of Technology
From Algorithm to Program (code) • How do we get the array of pixels from the current picture object? • We have used Pixel[] pixelArray = picture.getPixels(); • But we want to get the array of pixels from the current object • So we can use the keyword this Pixel[] pixelArray = this.getPixels(); • Or we can leave off the this Pixel[] pixelArray = getPixels(); Georgia Institute of Technology
Loop Algorithm to Code • How to write (code) the loop? • Use a while loop with a counter for the index starting at 0 int index = 0; • Loop while the index is less than the length of the array while (index < pixelArray.length) • Get the current pixel from the array of pixels for the current index Pixel pixelObj = pixelArray[index]; Georgia Institute of Technology
Loop Algorithm to Code - Continued • Get the red value at the pixel int value = pixelObj.getRed(); • Decrease the red value by 0.5 value = value * 0.5; • Set the pixel red value pixel.setRed(value); • Add one to (increment) the index • index = index + 1; Georgia Institute of Technology
public void decreaseRed() { Pixel[] pixelArray = this.getPixels(); Pixel pixelObj = null; int index = 0; // loop through all the pixels while(index < pixelArray.length) { // get the current pixel pixelObj = pixelArray[index]; // get the red value int value = pixelObj.getRed(); // decrease the red value value = value * 0.5; // set the pixel red pixelObj.setRed(value); // increment the index index = index + 1; } } Decrease Red Method Georgia Institute of Technology
Comments • Comments are explanations of your code to help people understand your code • They are ignored by the compiler • There are several kinds in Java // a comment that lasts to the end of the line /* a comment that can take up several lines until a */ /** a Javadoc comment that is used to create html documentation of your code */ Georgia Institute of Technology
Loss of Precision • If you try the code on the previous slide you will get a compiler error • Possible loss of precision • It is complaining about putting a double value into a int variable • Loss of fractional part Georgia Institute of Technology
Casting to Solve Loss of Precision Error • It will compile if we tell the compiler we know about the possible loss of precision • And that it is intended • By using a cast to int value = (int) (value * 0.5); • Notice that we cast the result of the multiplication back to an integer • Casting is forcing a value into a type (type) expression Georgia Institute of Technology
Move Declarations Outside Loops • When you need a variable in a loop it is best to declare it before the loop • Otherwise you are declaring a new variable each time through the loop • Which is slower than just changing the value associated with the variable • In some languages you must declare all variables at the beginning of a method (function) • In Java you can declare variables anywhere in a method • As long as you declare them before you use them Georgia Institute of Technology
Shortcuts for Common Operations • In programming you often need to add one to a value index = index + 1; • You may use the shortcut index++; or ++index; • If you wanted to subtract 1 instead index = index – 1; index--; or -- index; Georgia Institute of Technology
/** * Method to decrease the red * by 50% in a picture */ public void decreaseRed() { Pixel[] pixelArray = this.getPixels(); Pixel pixelObj = null; int index = 0; int value = 0; // loop through all the pixels while(index < pixelArray.length) { // get the current pixel pixelObj = pixelArray[index]; // get the red value value = pixelObj.getRed(); // decrease the red value value = value * 0.5; // set the pixel red pixelObj.setRed(value); // increment the index index++; } } Decrease Red Method Version 2 Georgia Institute of Technology
Decrease Red Exercise • In DrJava • Add the method decreaseRed() to Picture.java • Before the last } which ends the class definition • Compile the method • Click the Compile All button • Test it by doing the following in the interactions pane > String fileName = "C:/intro-prog-java/mediasources/caterpillar.jpg"; > Picture picture1 = new Picture(fileName); > picture1.explore(); > picture1.decreaseRed(); > picture1.explore(); Georgia Institute of Technology
Tracing Code • An important skill to develop is the ability to trace code • Also called walking through or stepping through your code • Look at each line and predict what will happen • Show the variables and their values Georgia Institute of Technology
Step Through decreaseRed() • A picture object was created from the file “caterpillar.jpg” and then was sent the message decreaseRed() • The picture object was implicitly passed to the method decreaseRed() and can be referred to by this • The array of pixel objects was returned from sending getPixels() to the picture object Pixel[] pixelArray = this.getPixels(); • Some variables were declared for later use in the loop Pixel pixelObj = null; int index = 0; int value = 0; Georgia Institute of Technology
Step Through decreaseRed() - cont • The while loop tests if the index is less than the length of the array while (index < pixelArray.length) { • And if so it executes the statements in the body of the loop {} • It sets the variable pixelObj to the pixel at the current index in the array of pixels pixelObj = pixelArray[index]; • It gets the red value of that pixel value = pixelObj.getRed(); • it sets the value to the integer part of (red value * 0.5) value = (int) (value * 0.5); • It sets the pixel’s red to the new value pixelObj.setRed(value); • It increments the index value index++; Georgia Institute of Technology
R=252, G=254, B=251, X=0, Y=0 R=253, G=255, B=254, X=1, Y=0 R=254, G=254, B=254, X=2, Y=0 Memory Map of decreaseRed() width=329 height=150 • What does memory look like the first time through the loop? • How about the 2nd time through? • How about the 3rd time through? • How about the last time through? Picture: Class getPixels() … this pixels … pixel Pixel: Class getRed() setRed()… redValue = 252 index = 0 Georgia Institute of Technology
Increase Red • What if you want to increase red by 30% • How would you do that? • Multiplying by 0.5 reduces the red by 50% • Multiplying by 1.0 would keep the same red value • Multiplying by 1.3 would increase the red by 30% • Multiplying by 1.7 would increase the red by 70% Georgia Institute of Technology
Increase Red Algorithm • To increase the red value in a picture by 30% • Get the array of pixels from the picture • Set up an index to start at 0 • Check if the index is less than the length of the array • If it is go on to step 4 of the loop • If it isn’t jump to the first instruction after the loop • Get the pixel at the current index from the array of pixels • Get the red value at the pixel • Multiply the red value by 1.3 • Set the red value at the pixel to the reduced red value • Increment the index and go back to step 3 Georgia Institute of Technology
Increase Red: Algorithm to Code • The algorithm for this method is very similar to the algorithm for decrease red • Start with the code for decreaseRed • Change the line of code that multiplied the current red value by 0.5 to 1.3 • Change the name of the method • Change any comments that need changing Georgia Institute of Technology