Silly question about reading pixels math

Started by
7 comments, last by irreversible 4 years, 11 months ago

So i am about to read a 8bit pixel and want to convert the value to float (0..1) range

Like this

unsigned char r = get_pixel_from_img(x, y);

Now do i divide it by 255 or 256? :(

float fval = float ( r ) / x;

Advertisement

Think about it: a byte goes from 0..255, so 0.0..1.0 = divide by 255.0 :)

.:vinterberg:.

Hint:

The maximum value of an unsigned 8bit integer is 255. So which value do you get if you calculate 255/256? It is probably not 1 ;). More like 0.9xxxx  So divide by 255. :D

Greetings

Normally for [0..1] you'd divide it by 255.

(0..1) ... you mean narrowing the integer range 0..255 down to the interval excluding 0.0 and 1.0 ?

Edit ninja'd ninja'd ... 

Yeah, dont tell anyone i asked that...

I won't

I made my last off by one error just yesterday ;-)

Your secret is safe. 

If unsure, let the compiler figure it out for you ?. Here's two "generic" methods using limits.h:


constexpr auto ucharMax = std::numeric_limits<unsigned char>::max();
float value = pixel / float(ucharMax);
  

float value2 = pixel / float(UCHAR_MAX);

 

Or you could roll your own for any byte size (which in a general case is overwhelmingly likely but not actually guaranteed to be 8 bits)...


using byte_t = unsigned char;
const byte_t ucharMax = byte_t(0xffffffff); // support any size of uchar up to 64 bits

 

Or if you know the size of your byte... Use mad hax!

image.png.70080b55e9ef63378672fc51f3d84d90.png

This topic is closed to new replies.

Advertisement