[英]How to convert an image to a 0-255 grey scale image
我能夠使用以下Java方法將圖像轉換為灰度圖像。
public void ConvertToGrayScale(BufferedImage bufImage, int ImgWidth, int ImgHeight) {
for (int w = 0; w < ImgWidth; w++) {
for (int h = 0; h < ImgHeight; h++) {
Color color = new Color(bufImage.getRGB(w, h));
int ColAvgVal = ((color.getRed() + color.getGreen() + color.getBlue()) / 3);
Color avg = new Color(ColAvgVal, ColAvgVal, ColAvgVal);
bufImage.setRGB(w, h, avg.getRGB());
System.out.println(avg.getRGB());
}
}
}
“的System.out.println(avg.getRGB());” 用於查看像素強度,但所有灰度級都是負值,而不是0-255之間 。
我做錯了嗎? 如何將圖像轉換為像素強度在0-255之間的灰度圖像。
謝謝
color.getRGB()
不返回0..255中的值,它返回由紅色,綠色和藍色值組成的整數,包括Alpha值。 據推測,這個alpha值是0xFF
,這使得任何組合顏色最終都為0xFFrrggbb
,或者,當你得到時,用小數寫成一個巨大的負數。
要查看指定的“灰色”級別,只需選中ColAvgVal
。
請注意,更好的RGB和灰度轉換公式是使用PAL / NTSC轉換 :
gray = 0.299 * red + 0.587 * green + 0.114 * blue
因為“全藍”的灰度應該比“全紅”和“全綠”更暗。
注意:如果直接使用此公式,請注意浮點舍入錯誤 。 從理論上講,它不應該返回0..255
之外的gray
值; 在實踐中, 它會 。 所以測試並鉗制結果。
另一個不需要每像素測試和鉗位的選項是使用僅整數版本:
gray = (299 * red + 587 * green + 114 * blue)/1000;
這應該只用很小的舍入誤差。
你可以檢查一下 。 我希望它可以幫到你。
你可以檢查一些不同的方法,如:
// The average grayscale method
private static BufferedImage avg(BufferedImage original) {
int alpha, red, green, blue;
int newPixel;
BufferedImage avg_gray = new BufferedImage(original.getWidth(), original.getHeight(), original.getType());
int[] avgLUT = new int[766];
for(int i=0; i<avgLUT.length; i++)
avgLUT[i] = (int) (i / 3);
for(int i=0; i<original.getWidth(); i++) {
for(int j=0; j<original.getHeight(); j++) {
// Get pixels by R, G, B
alpha = new Color(original.getRGB(i, j)).getAlpha();
red = new Color(original.getRGB(i, j)).getRed();
green = new Color(original.getRGB(i, j)).getGreen();
blue = new Color(original.getRGB(i, j)).getBlue();
newPixel = red + green + blue;
newPixel = avgLUT[newPixel];
// Return back to original format
newPixel = colorToRGB(alpha, newPixel, newPixel, newPixel);
// Write pixels into image
avg_gray.setRGB(i, j, newPixel);
}
}
return avg_gray;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.