Java awt中的getRGB(x,y)为每个像素返回相同的值

问题描述 投票:-5回答:2

我试图浏览一个图像并从所有像素中获取每个RGB颜色值并处理它们。但我得到所有像素相同的RGB值。显然这是错误的。

我在Java awt中使用了bufferedimage对象的getRGB(x,y)方法。知道这里有什么问题吗?

编辑:

我遇到了问题,将图像转换为缓冲图像会出现一些错误。我没有在缓冲图像中绘制图像。以下代码现在按预期工作。

    public void printImgDetails(Image img) {

    // get the sizes of the image
    long heigth = img.getHeight(null);
    long width = img.getWidth(null);

    // hashSet to hold all brightness values
    HashSet<Float> set = new HashSet<Float>(0);

    BufferedImage bimage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_BYTE_GRAY);
    int rgb;
    float[] hsv = new float[3];

    // Draw the image on to the buffered image
    Graphics2D bGr = bimage.createGraphics();
    bGr.drawImage(img, 0, 0, null);
    bGr.dispose();

    for (int i = 0; i < width; i++) {
        for (int j = 0; j < heigth; j++) {
            Color c = new Color(bimage.getRGB(j, i));

            int r = c.getRed();
            int g = c.getGreen();
            int b = c.getBlue();

            Color.RGBtoHSB(r, g, b, hsv);
            System.out.println("r: " + r + " g: " + g + " b: " + b);
            set.add(hsv[2]);
        }
    }

    // calculate the average brightness
    double sum = 0;
    for (float x : set) {
        sum += x;
    }
    double avg = sum / set.size();

    // print the results
    System.out.println("avg --> " + avg);

}

提前致谢。

java image-processing awt rgb
2个回答
0
投票

如果您为每个像素获得相同的值,则有几个可能的原因。

a)您的图像在每个像素中具有相同的值

b)你不要在调用getRGB之间改变x和y

c)你读了别的东西,但getRGB的返回值


0
投票

当我在编辑中写道时,通过在图像和bufferedimage之间进行转换存在问题。我忘记将图像绘制到bufferedimage中。而已。

© www.soinside.com 2019 - 2024. All rights reserved.