java 如何将像素转换为灰度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17117413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:03:00  来源:igfitidea点击:

How to convert pixels to gray scale?

javaimageprocessingmultimedia

提问by Little Child

Ok, I am using Processingwhich allows me to access pixels of any image as int[]. What I now want to do is to convert the image to gray-scale. Each pixel has a structure as shown below:

好的,我正在使用Processing它允许我将任何图像的像素作为int[]. 我现在想做的是将图像转换为灰度。每个像素具有如下所示的结构:

...........PIXEL............
[red | green | blue | alpha]
<-8--><--8---><--8--><--8-->  

Now, what transformations do I need to apply to individual RGB values to make the image gray-scale ??
What I mean is, how much do I add / subtract to make the image gray-scale ?

现在,我需要对各个 RGB 值应用哪些转换才能使图像灰度化?
我的意思是,我要加/减多少才能使图像灰度?

Update

更新

I found a few methods here: http://www.johndcook.com/blog/2009/08/24/algorithms-convert-color-grayscale/

我在这里找到了一些方法:http: //www.johndcook.com/blog/2009/08/24/algorithms-convert-color-grayscale/

回答by Renan

For each pixel, the value for the red, green and blue channels should be their averages. Like this:

对于每个像素,红色、绿色和蓝色通道的值应该是它们的平均值。像这样:

int red = pixel.R;
int green = pixel.G;
int blue = pixel.B;

pixel.R = pixel.G = pixel.B = (red + green + blue) / 3;

Since in your case the pixel colors seem to be stored in an array rather than in properties, your code could end up looking like:

由于在您的情况下,像素颜色似乎存储在数组中而不是属性中,因此您的代码最终可能如下所示:

int red = pixel[0];
int green = pixel[1];
int blue = pixel[2];

pixel[0] = pixel[1] = pixel[2] = (red + green + blue) / 3;

The general idea is that when you have a gray scale image, each pixel's color measures only the intensity of light at that point - and the way we perceive that is the average of the intensity for each color channel.

一般的想法是,当您拥有灰度图像时,每个像素的颜色仅测量该点的光强度 - 我们感知的方式是每个颜色通道强度的平均值。

回答by user2468700

The following code loads an image and cycle through its pixels, changing the saturationto zero and keeping the same hueand brightnessvalues.

以下代码加载图像并循环遍历其像素,将饱和度更改为零并保持相同的色调亮度值。

PImage img;

void setup () {
    colorMode(HSB, 100);
    img = loadImage ("img.png");
    size(img.width,img.height);
    color sat = color (0,0,0);

    img.loadPixels();

    for (int i = 0; i < width * height; i++) {
        img.pixels[i]=color (hue(img.pixels[i]), sat, brightness(img.pixels[i]));
    }

    img.updatePixels();
    image(img,0,0);
}