Reputation: 10036
I'm trying to do a pixel-by-pixel comparison of 20 png images stored in a cell array. For each pixel position (i,j) I want to find the pixel with the largest and smallest value from amongst the 20 images.
My current implementation seems to work, but as it's just a bunch of nested for loops it takes several minutes to finish executing. I'm looking for a more efficient method, does anyone have a suggestion? My current code is below.
min = 256;
max = -1;
for j = 1: xMax
for k = 1: yMax
for p = 1: 20
if imageArray{p}(j,k) > max
max = imageArray{p}(j,k);
end
if imageArray{p}(j,k) < min
min = imageArray{p}(j,k);
end
end
minImg(j,k) = min;
maxImg(j,k) = max;
min = 256;
max = -1;
end
end
Upvotes: 0
Views: 326
Reputation: 221614
Assuming the sizes of all those images to be the same, here's one efficient approach -
%// Get dimensions of each image
[nrows,ncols] = size(imageArray{1})
%// Convert the cell array to a 3D numeric array for vectorized operations
im = reshape(cell2mat(imageArray),nrows,ncols,[])
%// Use MATLAB builtins min and max along the third dimension for final output
minImg = min(im,[],3)
maxImg = max(im,[],3)
Upvotes: 2