modify pixel of image with 0.01

hi, i have a image i want to modify it each pixel of image having 0 value with 0.01. below is the code to replace the value 0 with 0.01. but it is not doing any thing.

code -

for (int y=0; y<contrast.rows; y++)
{
for (int x=0; x<contrast.cols; x++)
{
if(contrast.at<uchar>(y, x) ==0)
contrast.at<uchar>(y, x) = 0.01;
}
}


thanks

edit retag close merge delete

( 2014-11-14 04:33:38 -0500 )edit

If your image is of type 8UC1 (thats why I suppose that you are using uchar), its values are integers, not floating point, and is very likely that they are between 0(black) and 255(white). The least value that you can add is 1. Attributing 0.01 to a uchar variable will round it to 0.

( 2014-11-14 04:37:52 -0500 )edit

It's normal, since uchar is an integer type!!!

( 2014-11-14 04:49:57 -0500 )edit

i want to replace 0 value from 0.01. how can i do this?

( 2014-11-14 05:33:31 -0500 )edit

of course,it can not convert,because contrast.at<uchar>(y, x) means at point(x,y) the value type is unsigned char, if you want to replace the value from 0 to 0.01, at first, you should convert contrast to double or float type ,for example contrast.at<float>(y,x)=0.01

( 2014-11-14 06:05:27 -0500 )edit

Sort by ยป oldest newest most voted

the short answer is: you can't.

the longer one: a uchar Mat holds integer values, 0,1,2,3,...255. so assigning 0.01 will lead to rounding to the nearest integer, 0.

a value of 0.01 would probably only make sense for a float image in the [0..1] range, so:

Mat contrast = ... // CV_8U
Mat contrast_f;
contrast.convertTo( contrast_f, CV_32F, 1.0/255);

for (int y=0; y<contrast_f.rows; y++)
{
for (int x=0; x<contrast_f.cols; x++)
{
if(contrast_f.at<float>(y, x) ==0)
contrast_f.at<float>(y, x) = 0.01f;
}
}


if you still want to keep your uchar contrast image, the smallest non-0 value you can assign is 1 (while the largest is 255).

more