“无损”浮点数到 BYTE 的转换
我正在使用 libnoise 在 1024x1024 地形网格上生成 Perlin 噪声。我想将其浮点输出转换为 0 到 255 之间的字节。问题最终是一个数学问题:如何将实区间 (-1,1) 中的值转换为整数 1 (0,255) 最小化损失?
I'm using libnoise to generate Perlin noise on a 1024x1024 terrain grid. I want to convert its float output to a BYTE between 0 and 255. The question is ultimately a math one: how can I convert a value in the real interval (-1,1) to the integer one (0,255) minimizing loss?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的输入范围不包括端点,则此公式将为您提供 [0, 255] 中的数字:
如果您包括端点(然后通常写为 [-1,1] 而不是 (-1,1)),您将需要
x == 1.0
的特殊情况将其向下舍入为 255。This formula will give you a number in [0, 255] if your input range excludes the endpoints:
If you are including the endpoints (and then it usually written [-1,1] rather than (-1,1)) you will need a special case for
x == 1.0
to round that down to 255.最好的方法可能取决于 (-1,1) 中浮点数的分布;如果在某些区域中它们较多,而在某些区域中则较少,您可能希望以牺牲后者为代价来提高前者的“精度”。基本上,如果您有一个在此间隔定义的输出的概率函数,您可以将 (0,1)(概率值的间隔)拆分为 256 个相等的子间隔,并且对于每个给定的浮点数,您计算为哪个子间隔其概率函数值下降。对于噪声,概率函数(或至少应该)接近线性,因此马克·拜尔斯的答案也许是正确的选择。
The best way might depend on the distribution of floats in (-1,1); if in some areas there are more of them and in some there are less, you might want to increase the "precision" in the former at the expense of the latter. Basically, if you have a probability function for the output defined at this interval, you may split (0,1) - the interval of probability values - to 256 equal sub-intervals, and for each given float you calculate into which sub-interval its probability function value falls. For noise the probability function is (or at least should be) close to linear, so perhaps the answer of Mark Byers is the way to go.