If a variable holds a bunch of images, what does (:, :, 1, i) mean?

8 views (last 30 days)
Part of the code -
img = dicomread('example.dcm');
for i=1:100
data(:, :, i) = img(:, :, 1, i);
end

Accepted Answer

Guillaume
Guillaume on 20 Jan 2020
The code you have assumes that the file contains a multiframe image with at least 100 frames. If the file has less frames the code will error and if it has more, it will miss these extra frames. It would be much better to use the actual number of frames instead of hardcoding a constant:
for i = 1:size(img, 4) %go over all the frames, however many there are
img(:, :, :, i) is a 3D matrix, representing the RGB values of frame i, where img(:, :, 1,i) is the red channel, img(:, :, 2, i) is the green channel and img(:, :, 3, i) the blue channel. In effect your code copies all the red channels into a new 3D matrix and discard the green and blue channels. Possibly the code expects the images to be grayscale so all 3 channels should be equal.
The loop is completely unnecessary, the same can be achieve simply with:
img = dicomread('example.dcm')
data = squeeze(img(:, :, 1, :)); %img(:, :, 1, :) will result in a H x W x 1 x NumFrames matrix. squeeze converts that into a H x W x NumFrames matrix
  2 Comments
Xiq
Xiq on 20 Jan 2020
Thanks for the reply!
I have used the same number of frames in the code as are in the file, so that's good.
I forgot to mention that the images are all 16 bit grayscale.
If I am understanding correctly, the purpose of the loop (and your better alternative) is to eliminate color information, right?
Guillaume
Guillaume on 20 Jan 2020
Yes, the images are stored as true colour images, but if they all they contain is greyscale information, then R == G == B, so the code just copy the red channel and discard the green and blue since they are identical.
You can easily check that it is the case
%syntax for R2018b or later
assert(all(diff(img, [], 3) == 0, 'all'), 'At least one pixel is not pure greyscale'); %check that R == G == B for all pixels of all frames
%syntax for R2018a or earlier
assert(all(all(all(diff(img, [], 3) == 0)))), , 'At least one pixel is not pure greyscale'); %check that R == G == B for all pixels of all frames

Sign in to comment.

More Answers (1)

Rik
Rik on 20 Jan 2020
In the case of a 3D array, the last dimension is generally the z direction, although it can also be the different color channels (e.g. in an RGB image). If you have 4 dimensions, there are again two options. The first option is that the third is z and the fourth is time, and the second option is that the third is color and the fourth is the z direction (which is what the montage function assumes).
The only way to tell is from context and metadata. The rest of your question is basic Matlab syntax.

Tags

Community Treasure Hunt

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

Start Hunting!