将浮点范围转换/量化到整数范围 [英] Convert/Quantize Float Range to Integer Range

查看:410
本文介绍了将浮点范围转换/量化到整数范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在[0,1]范围内有一个浮点数,我想量化并存储在一个无符号的字节。听起来很简单,但事实上它非常复杂:

显而易见的解决方案如下所示:

<$ (unsigned char)(a * 255.0f); p $ p> 无符号字符QuantizeFloat(float a)
{




$ b $ p
$ b这个工作到目前为止,我得到的所有数字从0到255,但整数的分布是不均匀的。如果a正好是 1.0f ,那么函数只返回 255 。不是一个好的解决方案。

如果我做适当的四舍五入,我只是改变了这个问题:

  unsigned char QuantizeFloat(float a)
{
return(unsigned char)(a * 255.0f + 0.5f);

$ / code>

这里的结果 0 只覆盖浮点范围的一半,而不是任何其他数字。



如何在浮点范围的均匀分布下进行量化?理想情况下,如果我量化均匀分布的随机花车,我希望得到一个平均分布的整数。

有什么想法吗?

< hr>

btw:另外我的代码是在C这个问题是语言不可知的。对于非C人员:假设 float int 转换会截断浮点数。



编辑:因为我们在这里有一些困惑:我需要一个映射,将最小的输入float(0)映射到最小的unsigned char, (1.0f)到最高的无符号字节(255)。

解决方案

如何 a * 256f 检查减少256到255?例如:
$ b $ pre $ return(unsigned char)(min(255,(int)(a * 256f)));

(对于你平台上的一个合适的min函数 - 我不记得它的C函数。 )

基本上你想把范围分成256等份,这就是应该做的。 1.0到256的边界情况,要求舍去只是因为域包含在两端。


Say I have a float in the range of [0, 1] and I want to quantize and store it in an unsigned byte. Sounds like a no-brainer, but in fact it's quite complicated:

The obvious solution looks like this:

unsigned char QuantizeFloat(float a)
{
  return (unsigned char)(a * 255.0f);
}

This works in so far that I get all numbers from 0 to 255, but the distribution of the integers is not even. The function only returns 255 if a is exactly 1.0f. Not a good solution.

If I do proper rounding I just shift the problem:

unsigned char QuantizeFloat(float a)
{
  return (unsigned char)(a * 255.0f + 0.5f);
}

Here the the result 0 only covers half of the float-range than any other number.

How do I do a quantization with equal distribution of the floating point range? Ideally I would like to get a equal distribution of integers if I quantize equally distributed random floats.

Any ideas?


Btw: Also my code is in C the problem is language-agnostic. For the non-C people: Just assume that float to int conversion truncates the float.

EDIT: Since we had some confusion here: I need a mapping that maps the smallest input float (0) to the smallest unsigned char, and the highest float of my range (1.0f) to the highest unsigned byte (255).

解决方案

How about a * 256f with a check to reduce 256 to 255? So something like:

return (unsigned char) (min(255, (int) (a * 256f)));

(For a suitable min function on your platform - I can't remember the C function for it.)

Basically you want to divide the range into 256 equal portions, which is what that should do. The edge case for 1.0 going to 256 and requiring rounding down is just because the domain is inclusive at both ends.

这篇关于将浮点范围转换/量化到整数范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆