Home > Java > javaTutorial > body text

In Java OpenCV, convert image to grayscale without using any method

王林
Release: 2023-08-26 14:53:16
forward
1044 people have browsed it

Convert color image to grayscale.

  • Get the red, green and blue values ​​​​of each pixel

  • Get the average of these 3 colors.

  • Replace RGB values ​​with average.

  • Create a new pixel value based on the modified color.

  • Set the new value to pixels.

Example

import java.io.File;
import java.io.IOException;
import java.awt.Color;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
public class Color2Grey {
   public static void main(String args[])throws IOException {
      //Reading the image
      File file= new File("D:\Images\car.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();
            //Finding the average of the red green blue values
            int average = (red+green+blue)/3;
            //Creating new Color object
            color = new Color(average, average, average);
            //Setting new Color object to the image
            img.setRGB(x, y, color.getRGB());
         }
      }
      //Saving the modified image
      file = new File("D:\Images\grey_image.jpg");
      ImageIO.write(img, "jpg", file);
      System.out.println("Done...");
   }
}
Copy after login

Enter

在Java OpenCV中,不使用任何方法将图像转换为灰度图

Output

在Java OpenCV中,不使用任何方法将图像转换为灰度图

The above is the detailed content of In Java OpenCV, convert image to grayscale without using any method. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template