im2uint16 makes images binary (to convert images from double to uint16)

6 views (last 30 days)
I adjusted an image (uint16) using "imadjust" function.
The result image matrix is double, so I tried to convert it to uint16 using "im2uint16", but the result becomes binary (0 or 2^16-1).
How can I fix this?
My script is below, I am adjsuting a image stack.
% adjust images: stack0 (300x300x73 uint16)
range_in = [0 1]; %[0 1] for full range, [] for auto 1% saturation
range_out = []; %[] for "0-1" for imadjust output
stack_adjusted = nan(nx,ny,nfoi);
for f=foi
stack_adjusted(:,:,f) = imadjust(stack0(:,:,f),range_in,range_out);
end
%stack1=im2uint16((2^16-1)*stack_adjusted);
stack1=im2uint16(stack_adjusted);
if fInvertedImage
stack2 = imcomplement(stack1);
else
stack2 = stack1;
end

Accepted Answer

DGM
DGM on 28 Aug 2021
Edited: DGM on 28 Aug 2021
The image returned by imadjust() is of class 'double', but it's scaled as if it were still uint16. Im2uint16() will assume the image is normalized, given its class. When it denormalizes, all non-black content gets pushed out of the available range.
Normally, the output of imadjust() inherits its class (and scaling) from the input image. In this case, you've forced the output class to be 'double' in the preallocation using a NaN array. (NaN can't be represented in integer classes). You can use zeros() instead, and specify the class to match the expected output.
stack_adjusted = zeros(nx,ny,nfoi,class(stack0)); % preallocate
for f = 1:nfoi % i'm assuming you meant all frames?
stack_adjusted(:,:,f) = imadjust(stack0(:,:,f),range_in,range_out);
end
% output doesn't need conversion anymore, since it's already uint16
  3 Comments
DGM
DGM on 28 Aug 2021
If you use class(stack0) instead of explicitly specifying 'uint16', the preallocated array will be correct even when stack0 isn't uint16. I don't know if that will ever happen in your case.

Sign in to comment.

More Answers (0)

Categories

Find more on Convert Image Type in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!