Jump to content
  • Advertisement
_WeirdCat_

C++ Silly question about reading pixels math

Recommended Posts

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;

Share this post


Link to post
Share on other sites
Advertisement
Posted (edited)

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

Edited by vinterberg
spelling

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
Share on other sites
Posted (edited)

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 ... 

Edited by Green_Baron

Share this post


Link to post
Share on other sites
Posted (edited)

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

Edited by irreversible

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!