problem assigning integer values in image to NaN
Show older comments
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
More Answers (1)
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...
Categories
Find more on Image Arithmetic in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!