This happens because red is unsigned char
, which is a number in 0 to 255 range. However, you expect red
to behave like integer.
So given that
red = 255
red = red*127/255 + 128
When the program multiplies red*127 the result will overflow because its value will be greater than 255, and so the answer will be 0
(because 255*127 modulo 255 = 0). Hence you get red = red*127/255 + 128 = (255*127 modulo 255) / 255 + 128 = 0 /255 + 128 = 128
To fix this, you can cast red
to float when you do arithmetic operations on it, for example:
red = (float)red * 127 / 255
Edit
As pointed out by William red
is a cv::Mat
of type CV_8U
. You can convert the image to CV_32F
type for calculations and then convert it back. For example (this is C++ code):
Mat red_float;
red.convertTo(red_float,CV_32F);
red_float = red_float*RMAX/255+128;
red_float.convertTo(red,CV_8U);