📜  Java DIP-灰度转换

📅  最后修改于: 2020-12-14 05:36:23             🧑  作者: Mango


为了将彩色图像转换为灰度图像,您需要使用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. Method & Description
1

brighter()

It creates a new Color that is a brighter version of this Color.

2

darker()

It creates a new Color that is a darker version of this Color.

3

getAlpha()

It returns the alpha component in the range 0-255.

4

getHSBColor(float h, float s, float b)

It creates a Color object based on the specified values for the HSB color model.

5

HSBtoRGB(float hue, float saturation, float brightness)

It converts the components of a color, as specified by the HSB model, to an equivalent set of values for the default RGB model.

6

toString()

It returns a string representation of this Color.

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

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

输出

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

原始图片

灰度转换教程

灰度图像

Java图像处理教程