How to create a mirror image using Java OpenCV library?


To create a mirror image

  • Read the required image using ImageIO.read() method.

  • Get the height and width of the image.

  • Create an empty buffered image to store the result

  • Using nested for loops traverse through each pixel in the image.

  • Iterate the width of the image from right to left.

  • Get the pixel value using the getRGB() method.

  • Set the pixel values to the result image object using the setRGB() method, by replacing the new width values.

Example

import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class MirrorImage {
   public static void main(String args[])throws IOException {
      //Reading the image
      File file= new File("D:\Images\tree.jpg");
      BufferedImage img = ImageIO.read(file);
      //Getting the height and with of the read image.
      int height = img.getHeight();
      int width = img.getWidth();
      //Creating Buffered Image to store the output
      BufferedImage res = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
      for(int j = 0; j < height; j++){
         for(int i = 0, w = width - 1; i < width; i++, w--){
            int p = img.getRGB(i, j);
            //set mirror image pixel value - both left and right
            res.setRGB(w, j, p);
         }
      }
      //Saving the modified image
      file = new File("D:\Images\mirror_image.jpg");
      ImageIO.write(res, "jpg", file);
      System.out.println("Done...");
   }
}

Input

Output

Updated on: 09-Apr-2020

486 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements