4

我在 android 上的 opengl es 中使用颜色拾取,我正在计算一个颜色键以将其与我从 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));
}

首先将 float 值转换为 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

也许我的计算方法不正确?有谁知道如何避免这些偏差?

4

2 回答 2

2

例如如果你设置红色浮点数(31 / 255),我认为转换是这样的。

如果颜色格式为 RGB565(默认),则 31 (0001_1111) 转换为 3(0000_0011)

然后我们使用 glReadPixels() 来获取值

3(0000_0011) 转换为 24(0001_1000)

总之,如果您将红色设置为 31,您最终将得到 24。

消除舍入误差的关键是从 RGB565 转换为 RGB88 的方法,而您没有这样做。

你可以试一试。祝你好运。

于 2011-10-15T11:59:05.183 回答
1

Java 字节是有符号的。

如果您将 0xe4 视为无符号,则 -28 = 带符号字节中的 0xe4 = 十进制 228。
228/255 = 0.894 浮点数

于 2011-01-12T20:56:54.033 回答