problem assigning integer values in image to NaN

조회 수: 12 (최근 30일)
Sami
Sami 2017년 9월 15일
댓글: Matt J 2024년 1월 16일
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);

채택된 답변

Image Analyst
Image Analyst 2017년 9월 15일
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
Qian
Qian 2024년 1월 16일
Can I do it without change the data to single or double because the data can be huge in double format?
Matt J
Matt J 2024년 1월 16일
Then use singles.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

dpb
dpb 2017년 9월 15일
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!

Translated by