1
votes

I've imported a set of images in MATLAB, and I've converted them to grayscale. I must now create an image stack, "a 3D matrix of grayscale images". After this, I must create a 1D image intensity array by taking the "double mean of each layer of the image stack". Here is my code thus far (I import just a few images):

for i=139:141

string2 = num2str(i);

% Concatenate several strings, produce file name
str = [string, string2, string3];

% Read image
a = imread(str);

% Get image dimensions
size(a)

% Convert to grayscale
b = rgb2gray(a);

'size(a)' yields '1728 x 2592 x 3'. This is true for all images. I'm wondering how I can create the 3D matrix of grayscale images, and I'm wondering how I can create the 1D image array mentioned above. I'm assuming, perhaps incorrectly, that "double mean" means

mean(mean(...)).

For the 3D matrix, I have

% Pre-allocate 3D matrix
ImStack = zeros(1728, 2592, 3, class(b));

% Add images to ImStack
ImStack(:,:,1) = b;

This follows a template I found on the MathWorks help forum,

b= zeros(2000,2000,number_of_images,class(a));

b(:,:,1) = a;

However, I am unsure how to proceed with creating the 1D image intensity array. Your advice would be greatly appreciated. Thank you.

1

1 Answers

5
votes

Your code is most of the way there. However, there is a problem in this line:

ImStack(:,:,1) = b;

This places each image in the first plane of the image stack, and it will overwrite the last one in the same position. You need to use a different index for each image, like this:

ImStack(:,:,i-138) = b;  % subtract 138 because i starts at 139 in your code

When finished you can find the mean very easily by averaging along the third dimension:

ImMean = mean(ImStack,3);

One other note: if you have too many images, creating a stack that holds all of them at once could cause you to run short on memory. An alternative way to come up with the average is to add each image in a running sum, and at the end divide by the total number of images.