2015-10-14 96 views
0

任何人都可以看到什麼問題是當我嘗試將我的8位圖像轉換爲4位圖像?轉換8位圖像到4位圖像

我使用的是8位圖像測試發現這裏:http://laurashoe.com/2011/08/09/8-versus-16-bit-what-does-it-really-mean/

你可以告訴4位圖像看起來應該像,但礦幾乎是純黑色。

 // get color of the image and convert to grayscale 
     for(int x = 0; x <img.getWidth(); x++) { 
      for(int y = 0; y < img.getHeight(); y++) { 
       int rgb = img.getRGB(x, y); 
       int r = (rgb >> 16) & 0xF; 
       int g = (rgb >> 8) & 0xF; 
       int b = (rgb & 0xF); 

       int grayLevel = (int) (0.299*r+0.587*g+0.114*b); 
       int gray = (grayLevel << 16) + (grayLevel << 8) + grayLevel; 
       img.setRGB(x,y,gray); 
      } 
     } 
+0

對不起,這是相當晚,我一直在編碼。意思是說8位到4位。我改變了標題 – QQCompi

+0

好吧,但是如果我看到代碼,那麼您從源圖像中獲取的RGB值將作爲常規的24位RGB整數獲取。因此,我相信這裏顯示的是你所追求的:http://stackoverflow.com/questions/4801366/convert-rgb-values-int-integer-pixel(答案也顯示瞭如何將RGB int分成單獨的組件,注意與你的代碼不同)。 – Gimby

+0

您是不是指'&0xFF'而不是'0xF'?您的代碼僅從每個組件獲取較低的4位。 – Cinnam

回答

0

你應該用0xFF的不0xF,爲0xF意味着只有最後四位,wchich會告訴你幾乎一無所知的顏色,因爲在RGB色彩的是8位。

嘗試,如果這項工作:

// get color of the image and convert to grayscale 
     for(int x = 0; x <img.getWidth(); x++) { 
      for(int y = 0; y < img.getHeight(); y++) { 
       int rgb = img.getRGB(x, y); 
       int r = (rgb >> 16) & 0xFF; 
       int g = (rgb >> 8) & 0xFF; 
       int b = (rgb & 0xFF); 

       int grayLevel = (int) (0.299*r+0.587*g+0.114*b); 
       int gray = (grayLevel << 16) + (grayLevel << 8) + grayLevel; 
       img.setRGB(x,y,gray); 
      } 
     } 
0

由於代碼已經從問題編輯了,在這裏它與從註釋中確認的解決方案:

// get color of the image and convert to grayscale 
for(int x = 0; x <img.getWidth(); x++) { 
    for(int y = 0; y < img.getHeight(); y++) { 
     int rgb = img.getRGB(x, y); 

     // get the upper 4 bits from each color component 
     int r = (rgb >> 20) & 0xF; 
     int g = (rgb >> 12) & 0xF; 
     int b = (rgb >> 4) & 0xF; 

     int grayLevel = (int) (0.299*r+0.587*g+0.114*b); 

     // use grayLevel value as the upper 4 bits of each color component of the new color 
     int gray = (grayLevel << 20) + (grayLevel << 12) + (grayLevel << 4); 
     img.setRGB(x,y,gray); 
    } 
} 

注意,生成的圖像只看起來像4位灰度,但仍然使用int作爲RGB值。