How to I convert a binary (logical) image back into double, uint8, etc, without changing what the image looks like in binary?

65 views (last 30 days)
I took a grayscale image (.tif file) and converted it into binary using imbinarize(). This gave me the desired visual, but now I want to save that visual and use it for processing. The issue is that my processing method does not take logical inputs and I can not change it. Is there a way to perserve the binary visual and convert it into a double or uint8? I could just screenshot it then convert it to .tif, but that would be cheaty. Thank you!

Accepted Answer

DGM
DGM on 26 Jul 2023
Edited: DGM on 26 Jul 2023
If you want to change the numeric class of an image while retaining the image scale with respect to black/white, you normally use tools like im2uint8(), im2double(), etc. Those will also work on logical class images, where logical values become the class-dependent black/white values. For example:
A = logical([0 1 1 0]) % my logical image
A = 1×4 logical array
0 1 1 0
B = im2uint8(A) % represented in uint8
B = 1×4
0 255 255 0
C = im2double(A) % represented in double
C = 1×4
0 1 1 0
Depending on the file format you're saving to, this conversion may be done automatically if you pass a logical array to imwrite(), though formats such as PNG will support logical arrays, so you may choose to use im2uint8() beforehand in such a case.
Without knowing what subsequent processing is going to happen, bear in mind that while the logical and uint8 representations both contain the same information and will be rendered identically, they may not be compatible with the same operations.
For instance, you couldn't use the uint8 image directly for logical indexing
outpict = inpict(A); % this is basic logical indexing using a mask
outpict = inpict(B); % but this will result in an error
Also, you can imagine other scenarios where they wouldn't be equivalent due to the change in scale.
outpict = inpict.*A; % this wouldn't be implausible, since A is unit-scale
outpict = inpict.*B; % but this would result either in an error or an improperly-scaled result

More Answers (1)

Walter Roberson
Walter Roberson on 26 Jul 2023
img = imbinarize(imread('cameraman.tif'));
imshow(img); title('logical')
i8 = im2uint8(img);
imshow(i8); title('uint8');
id = im2double(img);
imshow(id); title('double');

Categories

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

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!