2015-10-14 323 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值。