How to convert a positive image to Negative to using OpenCV library?

JavaObject Oriented ProgrammingProgramming

Algorithm to convert an image to negative

  • Get the red green blue values of each pixel

  • Subtract each color value from 255 and save them as new color values.

  • Create a new pixel value from the modified colors.

  • set the new value to the pixel.

Implementation in Java

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

  • Get the height and width of the image.

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

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

  • Create a Color object bypassing the above-retrieved pixel value as parameter.

  • Get the red, green, blue values from the color object using the getRed(), getGreen() and getBlue() methods respectively.

  • Calculate the new red, green and blue values as specified in the algorithm.

  • Create a new Color object bypassing the new RGB values as parameters.

  • Get the pixel

  • Set the new pixel value(s) using the setRGB() method.

Example

import java.io.File;
import java.io.IOException;
import java.awt.Color;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class Color2Negative {
   public static void main(String args[])throws IOException {
      //Reading the image
      File file= new File("D:\\Images\\car3.jpg");
      BufferedImage img = ImageIO.read(file);
      for (int y = 0; y < img.getHeight(); y++) {
         for (int x = 0; x < img.getWidth(); x++) {
            //Retrieving the values of a pixel
            int pixel = img.getRGB(x,y);
            //Creating a Color object from pixel value
            Color color = new Color(pixel, true);
            //Retrieving the R G B values
            int red = color.getRed();
            int green = color.getGreen();
            int blue = color.getBlue();
            //Subtracting RGB from 255 to convert into negative
            red = 255-red;
            green = 255-green;
            blue = 255-blue;
            //Creating new Color object
            color = new Color(red, green, blue);
            int newPixel = color.getRGB();
            //Setting new Color object to the image
            img.setRGB(x, y, newPixel);
         }
      }
      //Saving the modified image
      file = new File("D:\\Images\\negative_image.jpg");
      ImageIO.write(img, "jpg", file);
      System.out.println("Done...");
   }
}

Input

Output

raja
Published on 09-Apr-2020 07:02:55
Advertisements