problem assigning integer values in image to NaN

21 views (last 30 days)
This seems to be a previously asked question, but I am having problem assigning some values (they are integer) in an image with NaN. None of the solutions posted before related to this topic worked in my case, so seeking help here.
I have two images. Lets say "B2" and "masked". I want to assign values from image "B2" to "masked" if pixel values of "masked" are zero. If they are above zero, I want to assign NaN values. Below is my code to do this. The code below works with no problem if I substitute NaN with certain number. But, if I try to assign NaN, it does not work. NaN by default gets converted to zero. I need to be able to assign NaN. Not sure what is happening here. Can someone show me a path?
pixelsToReplace = masked > 0;
masked(pixelsToReplace) = nan; % Do the actual masking.
pixelsToReplace=masked==0;
masked(pixelsToReplace)=B2(pixelsToReplace);

Accepted Answer

Image Analyst
Image Analyst on 15 Sep 2017
uints don't allow nans. If you want nans, which I seriously doubt you need them, then you'll need to use a double image, not a uint8 or uint16. Why do you think you need nans to do what you need to do? Actually, what do you need to do with masking? I'll show you how to do it without nans.
  4 Comments
Qian
Qian on 16 Jan 2024
Can I do it without change the data to single or double because the data can be huge in double format?

Sign in to comment.

More Answers (1)

dpb
dpb on 15 Sep 2017
NaN is a concept for floating point arrays only; if the image is one of the integer classes the assignment will be as you noted. It might be argued there should be a warning instead of just silent conversion to zero, but that is Matlab default behavior. Illustration--
>> a=int8(eye(3))
a =
1 0 0
0 1 0
0 0 1
>> a(a==0)=nan
a =
1 0 0
0 1 0
0 0 1
>>
No NaN; zero still there. OTOH,
>> b=double(a);
>> b(b==0)=nan
b =
1 NaN NaN
NaN 1 NaN
NaN NaN 1
>>
works as expected. End result -- if you really want the NaN placeholders you'll have to convert the array to float (single or double). This may have other ramifications for an image later on depending on what you're next steps are...

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!