4d Array converting RGB image into binary
2 views (last 30 days)
Show older comments
Hello, I want saved 3d images into a 4d array with following code:
for slice = 1 : length(filestrain)
filename = fullfile(foldertrain, filestrain(slice).name);
thisImage = imread(filename);
[rows, columns, numberOfColorChannels] = size(thisImage);
if numberOfColorChannels < 3
message = 'Error: Image is not RGB Color!';
uiwait(warndlg(message));
continue;
end
if rows ~= 1603 || columns ~= 1603
message = 'Error: Image is not 1603X1603!';
uiwait(warndlg(message));
continue; % Skip this image.
end
% Image is okay. Insert it.
XTrain(:,:,:,slice) = thisImage;
imshow(thisImage)
end
The images are zero padded images (1603x1603x3). The original images all have different sizes (cutted manually) and are partly very small like 321x97x3. I did this zero padding for the Input layer of a CNN.
when I am trying to display some images from the 4d Array with:
imshow(XTrain(:,:,2))
The image which is shown is like a binary image no RGB. I dont understand why. Is there a problem with the size of the images?
Thanks for your help
0 Comments
Accepted Answer
DGM
on 11 May 2021
Edited: DGM
on 11 May 2021
imshow(XTrain(:,:,2))
Is going to be a 4D monochrome image, which imshow won't like. I'm assuming you meant
imshow(XTrain(:,:,:,2))
which is a single frame from the stack.
One likely cause of the thresholding behavior is a mismatch between the image class and its data range. Imshow expects floating point images to be within [0 1]. If they're outside the range, they'll be clipped. This likely happens because you're preallocating your array like so:
XTrain = zeros(1603,1603,3,length(filestrain)); % this is implicitly double
You can pick a class when you preallocate the array (let's say uint8)
XTrain = zeros(1603,1603,3,length(filestrain),'uint8'); % this is explicitly uint8
and then make sure to cast and scale the images as you import them
XTrain(:,:,:,slice) = im2uint8(thisImage);
For what it's worth, MIMT has tools for batch importing into 4D arrays, with automatic padding, casting, and orientation. This loads a mix of monochrome and color images of various sizes and pads them with black to fit.
fprefix = fullfile(matlabroot,'toolbox','images','imdata')
fnames = {'c*.tif'};
instack = mimread(fprefix,fnames,'verbose');
instack = imstacker(instack,'padding',0,'gravity','c', ...
'outclass','uint8','verbose');
imshow2('instack','tools') % view 4D array
MIMT can be downloaded on the file exchange:
Documentation of mimread/imstacker is here:
More Answers (0)
See Also
Categories
Find more on Convert Image Type in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!