Presentation is loading. Please wait.

Presentation is loading. Please wait.

Manipulating Pictures, Arrays, and Loops

Similar presentations


Presentation on theme: "Manipulating Pictures, Arrays, and Loops"— Presentation transcript:

1 Manipulating Pictures, Arrays, and Loops
Barb Ericson Georgia Institute of Technology June 2005 Georgia Institute of Technology

2 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

3 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 For more about JPEG see See for more information about GIFF. See for more information about BMP. This windows format is not compressed. Georgia Institute of Technology

4 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

5 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 1 2 3 4 5 3 7 9 2 1 5 1 2 3 8 3 2 6 Think of seats in a row of a movie theater. They have an index too. They often start at 1. Java uses a 0-based index. This is a holdover from C when the index was really the distance from the beginning of the array. The distance from the beginning of the array to the first element is 0. Georgia Institute of Technology

6 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

7 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

8 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

9 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

10 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

11 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, … Originally the predefined colors where are lowercase names. However, the Java convention for constants is to use all uppercase letters. So the uppercase names for the predefined colors were added. Georgia Institute of Technology

12 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

13 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 Some people prefer to import each class by naming each one in an import statement. This is helpful for other people who may not know what package each class is in. However, if you are using several classes from the same package you can use the ‘*’ to import all classes in the same package. This will not extend to sub-packages. Georgia Institute of Technology

14 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

15 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

16 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(); Show will also repaint the picture. Georgia Institute of Technology

17 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(); java.awt.Color[r=117,g=91,b=73] > testColor = testColor.brighter(); java.awt.Color[r=167,g=130,b=104] Georgia Institute of Technology

18 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

19 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

20 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(); Type the above code in the interactions pane and see what happens. You can use the up arrow to pull up the last statement executed in the interactions pane and then use the left arrow to get to the number to change. Georgia Institute of Technology

21 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

22 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

23 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%? To decrease the red value by half multiply it by To increase the red value by 25% multiply it by 1.25. Georgia Institute of Technology

24 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

25 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

26 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

27 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? The counter is also often referred to as an index. Georgia Institute of Technology

28 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 The picture is a flowchart which shows the order the statements are executed in a program. A while loop allows you to repeat a series of statements until an expression is false. Georgia Institute of Technology

29 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

30 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); When you type the above code into DrJava you will need to do Shift-Enter when you type the while loop code in (so that it doesn’t try to evaluate the while loop till you have all the code entered. Georgia Institute of Technology

31 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 In this algorithm assume that you go on to the next step unless told to do otherwise. Georgia Institute of Technology

32 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

33 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(); This is a keyword that refers to the current object. If you leave off an object the compiler will assume you mean the current object (implicit this). Georgia Institute of Technology

34 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

35 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

36 Georgia Institute of Technology
Decrease Red Method 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; } Georgia Institute of Technology

37 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 */ Javadoc is a utility that comes with the JDK for creating html documentation from your source code (*.java files). Georgia Institute of Technology

38 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 Double clicking on an error in the Compiler Output pane will highlight the statement that caused the error and change the definitions pane to show you the problem. Georgia Institute of Technology

39 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

40 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

41 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; You can also use x += y as a shortcut for x = x + y, x-=y for x = x – y, x*=y for x=x*y, and x/=y for x = x / y. Georgia Institute of Technology

42 Decrease Red Method Version 2
/** * 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++; } Georgia Institute of Technology

43 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(); Use the picture explorer to check that the red values where reduced by 50%. Georgia Institute of Technology

44 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

45 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

46 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++; After each execution of the loop the test will be executed again. If the test is false execution will jump to the first statement after the body of the loop. If the test is true the statements in the loop will be executed again. Georgia Institute of Technology

47 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 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 pixel Pixel: Class getRed() setRed()… redValue = 252 index = 0 Georgia Institute of Technology

48 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

49 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

50 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

51 Georgia Institute of Technology
increaseRed Method /** * Method to increase the red by 30% */ public void increaseRed() { Pixel[] pixelArray = this.getPixels(); Pixel pixelObj = null; int value = 0; int index = 0; // loop through all the pixels while (index < pixelArray.length) // get the current pixel pixelObj = pixelArray[index]; // get the value value = pixelObj.getRed(); // increase value value = (int) (value * 1.3); // set the red value pixelObj.setRed(value); // increment the index index++; } Georgia Institute of Technology

52 Georgia Institute of Technology
Testing increaseRed Underwater pictures look too blue The water filters out most of the red color To test increase red: String file = “c:/intro-prog-java/mediasources/water.jpg”; Picture p = new Picture(file); p.explore(); p.increaseRed(); You may want to increase red several times to correct the too blue water picture. Use the explorer to check the red values in the original picture and the one with the red increased. Georgia Institute of Technology

53 Georgia Institute of Technology
Clear the Blue Values What if you want to clear the blue from a picture? Set all the blue values to 0 for all the pixels The algorithm is similar to decreaseRed() and increaseRed() except You don’t need to get the value out for blue and multiply it by some value and then set the blue value Just set the blue value to 0 Georgia Institute of Technology

54 Georgia Institute of Technology
Clear Blue Exercise In Picture.java Write the method public void clearBlue() That sets the blue value to 0 for all pixels in a picture Test with: String fileName = “c:/intro-prog-java/mediasources/caterpillar.jpg”; Picture p = new Picture(fileName); p.explore(); p.clearBlue(); When you clear the blue the white in the picture will look yellow. Georgia Institute of Technology

55 Georgia Institute of Technology
Faking a Sunset If you want to make an outdoor scene look like it happened during sunset You might want to increase the red But you can’t increase past 255 Another idea is to reduce the blue and green To emphasize the red Try to reduce the blue and green by 30% Georgia Institute of Technology

56 Faking a Sunset Algorithm
Reduce the blue and green 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 Set the blue value at the pixel to 0.7 times the original value Set the green value at the pixel to 0.7 times the original value Increment the index and go back to step 3 Georgia Institute of Technology

57 Georgia Institute of Technology
Faking a Sunset Method /** * Method to simulate a sunset by * decreasing the green * and blue */ public void makeSunset() { Pixel[] pixelArray = this.getPixels(); Pixel pixelObj = null; int value = 0; int i = 0; // loop through all the pixels while (i < pixelArray.length) { // get the current pixel pixelObj = pixelArray[i]; // change the blue value value = pixelObj.getBlue(); pixelObj.setBlue((int) (value * 0.7)); // change the green value value = pixelObj.getGreen(); pixelObj.setGreen((int) (value * 0.7)); // increment the index i++; } Programmers often use a variable named i for index. Georgia Institute of Technology

58 Georgia Institute of Technology
Testing makeSunset String file = “c:/intro-prog-java/mediasources/beach.jpg”; Picture pictureObj = new Picture(file); pictureObj.explore(); pictureObj.makeSunset(); Georgia Institute of Technology

59 Georgia Institute of Technology
For Loops Programmers like shortcuts Especially those that reduce errors And mean less typing We have been using a while loop with an index We had to declare the index variable and initialize it before the loop If you forget this there will be a compiler error We had to increment the index in the loop If you forget this it will be an infinite loop The shortcut for this is a For Loop Georgia Institute of Technology

60 Georgia Institute of Technology
For Loop Syntax for (initialization area; continuation test; change area) Initialization area Declare variables and initialize them Continuation test If true do body of loop If false jump to next statement after the loop Change area Change the loop variables Increment or decrement them Each of the three parts of a for loop are optional. However, the ‘;’s have to be there. You can declare and initialize more than one variable in the initialization area, just separate them with commas. Georgia Institute of Technology

61 Comparison of While and For Loops
int index = 0; while (index < pixelArray.length) { statements . index++; } for (int i=0; i < pixelArray.length; i++) { statements . } Programmers often use i as an index variable name. Even though the variable i is declared and initialized in the for loop it actually only is declared before the test. It is not repeated each time through the loop. Even though the increment is right after the continuation test in the for loop it doesn’t happen till after the last statement in the loop. Georgia Institute of Technology

62 Change clearBlue() to use a For Loop
/** * Method to clear the blue (set * the blue to 0 for all pixels) */ public void clearBlue() { Pixel pixelObj = null; // get the array of pixels Pixel[] pixelArray = this.getPixels(); // loop through all the pixels for (int i = 0; i < pixelArray.length; i++) { // get the current pixel pixelObj = pixelArray[i]; // set the blue on the pixel to 0 pixelObj.setBlue(0); } What is different about this mehod with the for loop? The index is now declared and initialized in the for loop not before the while loop. The change of the index is shown in the for loop even though it happens at the end of the loop body. Georgia Institute of Technology

63 Using System.out.println() in a Loop
One way to check what is happening in your program is to add System.out.println(expression); You might add this to the loop to check the value of ‘i’ during it. And to verify that the increment happens after the last statement in the loop Georgia Institute of Technology

64 Change to For Loop Exercise
Edit makeSunset() and change it from using a while loop to using a for loop Move the declaration of the index to the for loop initialization area Move the index increment to the for loop change area Execute the code to make sure it still works Georgia Institute of Technology

65 Georgia Institute of Technology
Negating an Image How would you turn a picture into a negative? White should become black 255,255,255 becomes 0,0,0 Black should become white 0,0,0 becomes 255,255,255 Georgia Institute of Technology

66 Georgia Institute of Technology
Negate Algorithm Subtract current value from 255 for red, green, and blue Get the array of pixels from the picture Loop starting an index at 0 and incrementing by 1 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 Set the red value to 255 – current red value Set the blue value to 255 – current blue value Set the green value to 255 – current green value Increment the index and go back to step 3 Georgia Institute of Technology

67 Georgia Institute of Technology
Negate Method /** * Method to negate the picture */ public void negate() { Pixel[] pixelArray = this.getPixels(); Pixel pixelObj = null; int redValue, blueValue, greenValue = 0; // loop through all the pixels for (int i = 0; i < pixelArray.length; i++) { // get the current pixel pixelObj = pixelArray[i]; // get the values redValue = pixelObj.getRed(); greenValue = pixelObj.getGreen(); blueValue = pixelObj.getBlue(); // set the pixel's color pixelObj.setColor( new Color(255 - redValue, 255 - greenValue, 255 - blueValue)); } Georgia Institute of Technology

68 Georgia Institute of Technology
Changing to Grayscale Grayscale ranges from black to white The red, green, and blue values are the same How can we change any color to gray? What number can we use for all three values? The intensity of the color We can average the colors (red + green + blue) / 3 Example ( ) / 3 = 90 To average x numbers get the sum of all the numbers and then divide by x. Georgia Institute of Technology

69 Georgia Institute of Technology
Grayscale Algorithm Set color values to the average of the original values Get the array of pixels from the picture Loop starting an index 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 Calculate the average of the current values Set the red value to the average Set the blue value to the average Set the green value to the average Increment the index and go to step 3 Georgia Institute of Technology

70 Georgia Institute of Technology
Grayscale Method /** * Method to change the picture to gray scale */ public void grayscale() { Pixel[] pixelArray = this.getPixels(); Pixel pixelObj = null; int intensity = 0; // loop through all the pixels for (int i = 0; i < pixelArray.length; i++) { // get the current pixel pixelObj = pixelArray[i]; // compute the average intensity intensity = (int) ((pixelObj.getRed() + pixelObj.getGreen() + pixelObj.getBlue()) / 3); // set the pixel color pixelObj.setColor(new Color(intensity,intensity,intensity)); } Georgia Institute of Technology

71 Georgia Institute of Technology
Testing Grayscale String file = “c:/intro-prog-java/mediasources/caterpillar.jpg”; Picture pictureObj = new Picture(file); pictureObj.explore(); pictureObj.grayscale(); Georgia Institute of Technology

72 Georgia Institute of Technology
Grayscale Result Georgia Institute of Technology

73 Georgia Institute of Technology
Luminance We perceive blue to be darker than red, and green Even when the same amount of light is reflected A better grayscale model should take this into account Weight green the highest (* 0.587) red less (* 0.299) and blue the very least (* 0.114) Georgia Institute of Technology

74 Grayscale with Luminance Exercise
Create a new method grayscaleWithLuminance Using the new algorithm for calculating intensity Georgia Institute of Technology

75 Georgia Institute of Technology
Summary Pictures have a grid of pixels You can change the picture by changing the color of the pixels You will need to repaint the picture Arrays let you store and retrieve values of the same type using an index You will need to import classes that you wish to use that aren’t in java.lang Loops allow you to execute a block of statements zero to many times Georgia Institute of Technology


Download ppt "Manipulating Pictures, Arrays, and Loops"

Similar presentations


Ads by Google