Java DIP - 灰度转换

为了将彩色图像转换为灰度图像,您需要使用 FileImageIO 对象读取图像的像素或数据,并将图像存储在 BufferedImage 对象中。其语法如下 −

File input = new File("digital_image_processing.jpg");
BufferedImage image = ImageIO.read(input);

此外,使用方法 getRGB() 获取像素值并对其执行 GrayScale() 方法。方法 getRGB() 将行和列索引作为参数。

Color c = new Color(image.getRGB(j, i));
int red = (c.getRed() * 0.299);
int green =(c.getGreen() * 0.587);
int blue = (c.getBlue() *0.114);

除了这三种方法之外,Color 类中还有其他方法,简要介绍 −

Sr.No. 方法 &描述
1

brighter()

它创建一个新的颜色,它是此颜色的更亮版本。

2

darker()

它创建一个新的颜色,它是此颜色的更暗版本。

3

getAlpha()

它返回 0-255 范围内的 alpha 分量。

4

getHSBColor(float h, float s, float b)

根据 HSB 颜色模型的指定值创建一个 Color 对象。

5

HSBtoRGB(float hue, float saturation, float bright)

将 HSB 模型指定的颜色成分转换为默认 RGB 模型的一组等效值。

6

toString()

返回此颜色的字符串表示形式颜色。

最后一步是将这三个值全部相加,然后再次将其设置为相应的像素值。其语法如下 −

int sum = red+green+blue;
Color newColor = new Color(sum,sum,sum);
image.setRGB(j,i,newColor.getRGB());

示例

以下示例演示了如何使用 Java BufferedImage 类将图像转换为灰度图像 −

import java.awt.*;
import java.awt.image.BufferedImage;

import java.io.*;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

public class GrayScale {

   BufferedImage  image;
   int width;
   int height;
   
   public GrayScale() {
   
      try {
         File input = new File("digital_image_processing.jpg");
         image = ImageIO.read(input);
         width = image.getWidth();
         height = image.getHeight();
         
         for(int i=0; i<height; i++) {
         
            for(int j=0; j<width; j++) {
            
               Color c = new Color(image.getRGB(j, i));
               int red = (int)(c.getRed() * 0.299);
               int green = (int)(c.getGreen() * 0.587);
               int blue = (int)(c.getBlue() *0.114);
               Color newColor = new Color(red+green+blue,
               
               red+green+blue,red+green+blue);
               
               image.setRGB(j,i,newColor.getRGB());
            }
         }
         
         File ouptut = new File("grayscale.jpg");
         ImageIO.write(image, "jpg", ouptut);
         
      } catch (Exception e) {}
   }
   
   static public void main(String args[]) throws Exception {
      GrayScale obj = new GrayScale();
   }
}

输出

执行给定示例时,它会将图像 digital_image_processing.jpg 转换为其等效的灰度图像,并将其写入硬盘上,名称为 grayscale.jpg

原始图像

灰度转换教程

灰度图像

Java 图像处理教程