我已经尝试将已经是黑白灰色的图片灰度化,然后变成黑色。
[当我尝试使用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位的位置读取图片有任何建议吗?用于图像分类。
问题在于将其添加到RealMatrix
的结果实例中:
data.addToEntry(countRows, 0, avg);
[The first two parameters of RealMatrix.addToEntry
are row and column.您将RealMatrix.addToEntry
用作countRows
,在每次读取像素后将其递增,而将row
用作0
。
应该应该是
column