如何从Java图片中获取0..255的颜色?

问题描述 投票:0回答:1

我已经尝试将已经是黑白灰色的图片灰度化,然后变成黑色。

[当我尝试使用Java对图片进行灰度处理时,我确实是这样:

    // This turns the image data to grayscale and return the data
    private static RealMatrix imageData(File picture) {
        try {
            BufferedImage image = ImageIO.read(picture);
            int width = image.getWidth();
            int height = image.getHeight();
            RealMatrix data = MatrixUtils.createRealMatrix(height * width, 1);
            // Convert to grayscale
            int countRows = 0;
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    // Turn image to grayscale
                    int p = image.getRGB(x, y);
                    int r = (p >> 16) & 0xff;
                    int g = (p >> 8) & 0xff;
                    int b = p & 0xff;

                    // calculate average and save
                    int avg = (r + g + b) / 3;
                    data.addToEntry(countRows, 0, avg);
                    countRows++;
                }
            }
            return data;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

我看到的问题是p是32位值,而我只想要8位值。即使图片已经是灰度的,p值也已经是32位值。那给我带来麻烦。

因此,如果我将一张灰色图片灰度化,它将变成黑色。或至少更暗。我想要p的0..255值,这是一个32位整数值。

您对如何在8位的位置读取图片有任何建议吗?用于图像分类。

java image grayscale
1个回答
0
投票

问题在于将其添加到RealMatrix的结果实例中:

data.addToEntry(countRows, 0, avg);

[The first two parameters of RealMatrix.addToEntry are row and column.您将RealMatrix.addToEntry用作countRows,在每次读取像素后将其递增,而将row用作0

应该应该是

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