【问题标题】:Convert Image to Grayscale with array matrix RGB java使用数组矩阵RGB java将图像转换为灰度
【发布时间】:2012-11-09 22:29:44
【问题描述】:

我正在创建一个图像过滤程序,我想借助数组矩阵将彩色图片转换为灰度图片。

这是我目前拥有的:

import java.awt.Color;
import se.lth.cs.ptdc.images.ImageFilter;

public class GrayScaleFilter extends ImageFilter {

    public GrayScaleFilter(String name){
        super(name);
    }

    public Color[][] apply(Color[][] inPixels, double paramValue){
        int height = inPixels.length;
        int width = inPixels[0].length;
        Color[][] outPixels = new Color[height][width];
        for (int i = 0; i < 256; i++) {
          grayLevels[i] = new Color(i, i, i);
        }

        for(int i = 0; i < height; i++){
            for(int j = 0; j < width; j++){
                Color pixel = inPixels[i][j];
            outPixels[i][j] = grayLevels[index];                    
            }
        }
        return outPixels;
    }
}

看来我应该使用这个公式:((R+G+B)/3)

我想创建一个这样的数组矩阵:

 Color[] grayLevels = new Color[256];
    // creates the color (0,0,0) and puts it in grayLevels[0],
    // (1,1,1) in grayLevels[1], ..., (255,255,255) in grayLevels[255]

这也是我想使用 grascale 时引用的类:

public abstract Color[][] apply(Color[][] inPixels, double paramValue);

protected short[][] computeIntensity(Color[][] pixels) {
    int height = pixels.length;
    int width = pixels[0].length;
    short[][] intensity = new short[height][width];
    for (int i = 0; i < height; i++) {
        for (int j = 0; j < width; j++) {
            Color c = pixels[i][j];
            intensity[i][j] = (short) ((c.getRed() + c.getGreen() + c
                    .getBlue()) / 3);
        }
    }
    return intensity;
}

关于我如何实现这一点的任何反馈?而不是使用outPixels[i][j] = new Color(intensity, intensity, intensity);

【问题讨论】:

    标签: java arrays matrix rgb


    【解决方案1】:

    以这种方式构建grayLevels 数组:

    for (int i = 0; i < 256; i++) {
      grayLevels[i] = new Color(i, i, i);
    }
    

    然后,当您需要某种颜色时,只需将其检索为grayLevels[index]

    【讨论】:

    • 我添加了循环并写道:outPixels[i][j] = new Color(grayLevels[index]);但它似乎没有工作
    • 应该是 outPixels = grayLevels[index]。我想目标是您不要创建那么多 Color 对象。
    • 您是否还需要实际构建 BufferedImage 并将其保存到磁盘的代码?
    • 我尝试按照您所说的进行设置,但出现错误“索引无法解析为变量”。我已经完成了构建图像的 GUI。
    • 索引是这个值:(short) ((c.getRed() + c.getGreen() + c.getBlue()) / 3)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    • 2014-12-22
    • 1970-01-01
    • 2011-02-06
    • 2021-04-02
    • 1970-01-01
    相关资源
    最近更新 更多