2010-09-28 27 views
4

我使用顏色在Android上的OpenGL ES採摘,我計算色鍵比較它的價值,我從glReadPixels獲得:顏色採摘機器人 - glReadPixels舍入誤差

ByteBuffer PixelBuffer = ByteBuffer.allocateDirect(4); 
PixelBuffer.order(ByteOrder.nativeOrder()); 
gl.glReadPixels(x, y, 1, 1, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, PixelBuffer); 
byte b[] = new byte[4]; 
PixelBuffer.get(b); 
String key = "" + b[0] + b[1] + b[2]; 

這個鍵可以用於與任何顏色手動計算:

public static byte floatToByteValue(float f) { 
    return (byte) ((int) (f * 255f)); 
} 

首先浮點值被轉換成的intValue然後CASTET到字節。浮點值描述顏色信道紅綠藍(從0.0f到1.0f)。 例如:0.0f被轉換爲255(現在的整數),然後從255到-1的字節

這工作正常,但opengl似乎使有些時候舍入錯誤。例如:

0.895 -> -28 and opengl returns -27 
0.897 -> -28 and opengl returns -27 
0.898 -> -28 and opengl returns -27 
0.8985 -> -27 and opengl returns -27 
0.899 -> -27 and opengl returns -26 
0.9 -> -27 and opengl returns -26 
0.91 -> -24 and opengl returns -24 

也許我的計算方法不正確?有沒有人有一個想法如何避免這些偏差?

回答

1

Java字節被簽名。

-28 =有符號字節= 0xe4 = 228十進制如果您將0xe4視爲無符號。
228/255 = 0.894浮點數

+0

確定但在java中沒有unsinged字節,所以如何將0.895轉換爲-27? – 2011-01-15 14:16:09

2

例如 如果你設置了紅色浮點數(31/255),我認爲轉換是這樣的。

31(0001_1111)轉變爲3(0000_0011)如果顏色格式爲RGB565(默認)

然後我們用glReadPixels()來獲取值

3(0000_0011)轉變爲24(0001_1000 )

總之,如果你爲紅色設置了31,你最終會得到24。

消除舍入誤差的關鍵是從RGB565轉換爲RGB88的方法,這是你沒有做的。

您可以試試。祝你好運。

+0

有人試過嗎?工作? – lacas 2012-01-02 08:00:07