Skip to content Skip to navigation

OpenStax-CNX

You are here: Home » Content » Java3012: Using Nested Loops to Process Pixels

Navigation

Recently Viewed

This feature requires Javascript to be enabled.
 

Java3012: Using Nested Loops to Process Pixels

Module by: R.G. (Dick) Baldwin. E-mail the author

Summary: Learn how to use nested for loops to process pixels on a row and column basis.

Preface

This module is one of a series of modules designed to teach you about Object-Oriented Programming (OOP) using Java.

The program described in this module requires the use of the Guzdial-Ericson multimedia class library. You will find download, installation, and usage instructions for the library at Java OOP: The Guzdial-Ericson Multimedia Class Library .

Viewing tip

I recommend that you open another copy of this document in a separate browser window and use the following links to easily find and view the images and listings while you are reading about them.

Images

Listings

Preview

In this module, you will learn how to use nested for loops to process pixels on a row and column basis.

Program specifications

Write a program named Prob01 that uses the class definition shown in Listing 1 along with Ericson's media library and the image file named Prob01.jpg to produce the graphic output images shown in Image 1 and Image 2 .

1
Image 1: Raw image.
Unmodified image of a beach scene.
2
Image 2: Modified image.
Mirrored image of the beach scene producing an image that looks like a beautiful lake.

Define new classes

You may define new classes as necessary to cause your program to behave as required, but you may not modify the class definition for the class named Prob01 given in Listing 1 .

Required text output

In addition to the two output images mentioned above, your program must display your name and the other line of text shown in Image 3 on the command-line screen.

3
Image 3: Required text output.
Display your name here. 
Picture, filename Prob01.jpg height 240 width 320

General background information

This program mirrors an image in such a way that the image in each quadrant is a mirror image of the image in the two adjacent quadrants as shown in Image 2 .

The top left quadrant is mirrored into the top right quadrant, and then the top half is mirrored into the bottom half.

Major evaluation areas

In order to successfully write this program, the student must be able to:

  • Examine the input and output images and determine how the input image has been modified to produce the output image.
  • Manipulate the individual pixels in the image to perform the required modifications.

Discussion and sample code

Will discuss in fragments

I will discuss this program in fragments. A complete listing of the program is provided in Listing 8 near the end of the module.

The driver class named Prob01

The driver class containing the main method is shown in Listing 1 .

4
Listing 1: The driver class named Prob01.
public class Prob01{
  public static void main(String[] args){
    Picture pic = new Prob01Runner().run();
    System.out.println(pic);
  }//end main method
}//end class Prob01

There is nothing in Listing 1 that I haven't explained in earlier modules.

The println statement in Listing 1 causes the second line of text to be displayed in Image 3 .

The constructor for the class named Prob01Runner

The constructor for the class named Prob01Runner is shown in Listing 2 .

5
Listing 2: The constructor for the class named Prob01Runner .
class Prob01Runner{
  public Prob01Runner(){
    System.out.println("Display your name here.");
  }//end constructor

The code in Listing 2 simply causes the first line of text in Image 3 to be displayed on the command line screen.

Beginning of the method named run

The code in the driver class in Listing 1 instantiates a new object of the Prob01Runner class and immediately calls the run method belonging to that object. The run method begins in Listing 3 .

6
Listing 3: Beginning of the method named run.
  public Picture run(){
    Picture pix = new Picture("Prob01.jpg");
    
    //Display the input picture.
    pix.explore();

    //Call the mirrorUpperQuads method to modify the top
    // half of the picture.
    pix = mirrorUpperQuads(pix);

A new Picture object

Listing 3 instantiates a new Picture object from an image file and saves a reference to that object in the local variable named pix .

Display the Picture object

Then Listing 3 calls the explore method on the reference producing the output image shown in Image 1 .

Modify top half of the picture

Finally, Listing 3 calls the method named mirrorUpperQuads to mirror the upper-left quadrant of the picture into the upper-right quadrant. A copy of a reference to the picture object is passed to the method and the value returned by the method is saved in the variable named pix . ( I will have more to say about this later.)

Put the explanation of the run method on hold

I will put the explanation of the run method on hold temporarily and explain the method named mirrorUpperQuads .

Beginning of the mirrorUpperQuads method

The beginning of the mirrorUpperQuads method is shown in Listing 4 .

7
Listing 4: Beginning of the mirrorUpperQuads method.
  private Picture mirrorUpperQuads(Picture pix){
    Pixel leftPixel = null;
    Pixel rightPixel = null;
    
    int midpoint = pix.getWidth()/2;
    int width = pix.getWidth();

Note that the method receives a copy of a reference to the picture.

Declare working variables

The code in Listing 4 begins by declaring a pair of local working variables of type Pixel . These variables will be used to hold information about individual pixels.

Compute width and midpoint of the image

Then Listing 4 computes and saves the width and the horizontal midpoint of the image.

Mirror pixel colors around the midpoint

Listing 5 uses a pair of nested for loops to copy the pixel colors on the left of the midpoint to corresponding mirror-image pixels on the right side of the midpoint.

8
Listing 5: Mirror pixel colors around the midpoint.
    for(int row = 0;row < pix.getHeight()/2;row++){
      for(int col = 0;col < midpoint;col++){
        leftPixel = pix.getPixel(col,row);
        rightPixel = pix.getPixel(width-1-col,row);
        rightPixel.setColor(leftPixel.getColor());
      }//end inner loop
    }//end outer loop

    return pix;
  }//end mirrorUpperQuads

Iterate on rows and columns

The outer loop in Listing 5 iterates down through each of the rows in the top half of the image.

The inner loop iterates across the left half of each row, copying the color of the pixels from the left half to the corresponding mirror-image pixels on the right half.

Return a reference to the modified object

Finally, Listing 5 returns a reference to the modified Picture object. The reference is assigned to the variable named pix in Listing 3 .

Superfluous but self-documenting code

Returning and storing a reference to the modified picture is superfluous and unnecessary. The code in Listing 3 already has a reference to the picture and that reference doesn't change just because the object to which it refers is modified.

However, I prefer this programming style because I consider it to be more self-documenting.

Remainder of the run method

Returning now to the run method, Listing 6 calls the method named mirrorHoriz to mirror the top half of the image into the bottom half. (I will explain the mirrorHoriz method shortly.)

9
Listing 6: Remainder of the run method.
    //Mirror the top half into the bottom half.
    pix = mirrorHoriz(pix);
    
    //Add your name and display the output picture.
    pix.addMessage("Display your name here.",10,20);
    
    pix.explore();
    
    return pix;

  }//end run

Display text on the image

Then Listing 6 calls the addMessage method on the reference to the picture to place the text near the upper-left corner as shown in Image 2 .

Display the modified image

After that, Listing 6 calls the explore method to display the modified image as shown in Image 2 .

Return a reference to the modified picture

Finally, Listing 6 returns the reference to the modified picture, which is saved in the variable named pic in Listing 1 .

As mentioned earlier, the variable named pic is passed to the println method in Listing 1 , causing the second line of text shown in Image 3 to be displayed on the command line screen.

The method named mirrorHoriz

Listing 7 shows the method named mirrorHoriz in its entirety. This method mirrors the top half of the picture into the bottom half.

10
Listing 7: The method named mirrorHoriz.
  private Picture mirrorHoriz(Picture pix){
    Pixel topPixel = null;
    Pixel bottomPixel = null;
    
    int midpoint = pix.getHeight()/2;
    int height = pix.getHeight();
    
    for(int col = 0;col < pix.getWidth();col++){
      for(int row = 0;row < midpoint;row++){
        topPixel = pix.getPixel(col,row);
        bottomPixel =
                   pix.getPixel(col,height-1-row);
        bottomPixel.setColor(topPixel.getColor());
      }//end inner loop
    }//end outer loop

    return pix;
  }//end mirrorHoriz
  //----------------------------------------------------//
  
}//end class Prob01Runner

Very similar to an earlier method

This method is very similar to the method named mirrorUpperQuads that I explained in Listing 4 and Listing 5 . If you understood that explanation, you should have no difficulty understanding the code in Listing 7 without further explanation.

End of Prob01Runner class

Listing 7 also signals the end of the class named Prob01Runner .

Run the program

I encourage you to copy the code from Listing 8 . Compile the code and execute it. Experiment with the code, making changes, and observing the results of your changes. Make certain that you can explain why your changes behave as they do.

Click here to download the required input image file.

Summary

In this module, you learned how to use nested for loops to process pixels on a row and column basis.

What's next?

You will learn to crop, flip, and combine pictures in the next module.

Online video links

Select the following links to view online video lectures on the material in this module.

Miscellaneous

This section contains a variety of miscellaneous information.

Note:

Housekeeping material
  • Module name: Java OOP: Using Nested Loops to Process Pixels
  • File: Java3012.htm
  • Published: 07/31/12
  • Revised: 02/14/13

Note:

Disclaimers:

Financial : Although the Connexions site makes it possible for you to download a PDF file for this module at no charge, and also makes it possible for you to purchase a pre-printed version of the PDF file, you should be aware that some of the HTML elements in this module may not translate well into PDF.

I also want you to know that, I receive no financial compensation from the Connexions website even if you purchase the PDF version of the module.

In the past, unknown individuals have copied my modules from cnx.org, converted them to Kindle books, and placed them for sale on Amazon.com showing me as the author. I neither receive compensation for those sales nor do I know who does receive compensation. If you purchase such a book, please be aware that it is a copy of a module that is freely available on cnx.org and that it was made and published without my prior knowledge.

Affiliation : I am a professor of Computer Information Technology at Austin Community College in Austin, TX.

Complete program listing

A complete listing of the program discussed in this module is shown in Listing 8 below.

11
Listing 8: Complete program listing.
/*File Prob01 Copyright 2008 R.G.Baldwin
Revised 12/16/08
*********************************************************/

public class Prob01{
  public static void main(String[] args){
    Picture pic = new Prob01Runner().run();
    System.out.println(pic);
  }//end main method
}//end class Prob01
//======================================================//

class Prob01Runner{
  public Prob01Runner(){
    System.out.println("Display your name here.");
  }//end constructor
  //----------------------------------------------------//
  public Picture run(){
    Picture pix = new Picture("Prob01.jpg");
    //Display the input picture.
    pix.explore();

    //Call the mirrorUpperQuads method to modify the top
    // half of the picture.
    pix = mirrorUpperQuads(pix);
    //Mirror the top half into the bottom half.
    pix = mirrorHoriz(pix);
    //Add your name and display the output picture.
    pix.addMessage("Display your name here.",10,20);
    pix.explore();
    return pix;

  }//end run
  //----------------------------------------------------//

  //This method mirrors the upper-left quadrant of a
  // picture into the upper-right quadrant.
  private Picture mirrorUpperQuads(Picture pix){
    Pixel leftPixel = null;
    Pixel rightPixel = null;
    int midpoint = pix.getWidth()/2;
    int width = pix.getWidth();
    for(int row = 0;row < pix.getHeight()/2;row++){
      for(int col = 0;col < midpoint;col++){
        leftPixel = pix.getPixel(col,row);
        rightPixel =
                   pix.getPixel(width-1-col,row);
        rightPixel.setColor(leftPixel.getColor());
      }//end inner loop
    }//end outer loop

    return pix;
  }//end mirrorUpperQuads
  //----------------------------------------------------//

  //This method mirrors the top half of a picture into
  // the bottom half.
  private Picture mirrorHoriz(Picture pix){
    Pixel topPixel = null;
    Pixel bottomPixel = null;
    int midpoint = pix.getHeight()/2;
    int height = pix.getHeight();
    for(int col = 0;col < pix.getWidth();col++){
      for(int row = 0;row < midpoint;row++){
        topPixel = pix.getPixel(col,row);
        bottomPixel =
                   pix.getPixel(col,height-1-row);
        bottomPixel.setColor(topPixel.getColor());
      }//end inner loop
    }//end outer loop

    return pix;
  }//end mirrorHoriz
  //----------------------------------------------------//
}//end class Prob01Runner

-end-

Content actions

Download module as:

Add module to:

My Favorites (?)

'My Favorites' is a special kind of lens which you can use to bookmark modules and collections. 'My Favorites' can only be seen by you, and collections saved in 'My Favorites' can remember the last module you were on. You need an account to use 'My Favorites'.

| A lens I own (?)

Definition of a lens

Lenses

A lens is a custom view of the content in the repository. You can think of it as a fancy kind of list that will let you see content through the eyes of organizations and people you trust.

What is in a lens?

Lens makers point to materials (modules and collections), creating a guide that includes their own comments and descriptive tags about the content.

Who can create a lens?

Any individual member, a community, or a respected organization.

What are tags? tag icon

Tags are descriptors added by lens makers to help label content, attaching a vocabulary that is meaningful in the context of the lens.

| External bookmarks