Working with Cell Arrays
4 views (last 30 days)
Show older comments
I'm doing some image analysis and am having a problem working with the cell arrays. I read in my images and they are stored in a cell array. I want to threshold every image for the different channels. And later on work with those thresholded images.
However, with the code I have below, for channel1bw, channel2bw, etc. I end up with a 90112*2048 double instead of a cell array for each image in the channel. For this example there are 44 images for each channel 44*2048=9012. I'd like the thresholded images to be stored in a vertical cell array, instead of all the pixel data in one matrix.
Any help would be appreciated. Also is there a cleaner way to code this? The for loops are redundant and I know it is a poor way to code.
channel1bw=[];
channel2bw=[];
channel3bw=[];
channel4bw=[];
channel5bw=[];
for x=1:length(channel1)
level=graythresh(channel1{x});
channel1bw=[channel1bw; im2bw(channel1{x},level)];
end
x=0;
for x=1:length(channel2)
level=graythresh(channel2{x});
channel2bw=[channel2bw; im2bw(channel2{x},level)];
end
x=0;
for x=1:length(channel3)
level=graythresh(channel3{x});
channel3bw=[channel3bw; im2bw(channel3{x},level)];
end
x=0;
for x=1:length(channel4)
level=graythresh(channel4{x});
channel4bw=[channel4bw; im2bw(channel4{x},level)];
end
x=0;
for x=1:length(channel5)
level=graythresh(channel5{x});
channel5bw=[channel5bw; im2bw(channel5{x},level)];
end
x=0;
Thanks for any help.
4 Comments
José-Luis
on 24 Jun 2014
I am sorry, but I don't follow. Does that mean that channelx is a cell array with images in it?
Answers (2)
José-Luis
on 24 Jun 2014
your_mat = ones([2048,2048,numel(channel1)];
for x=1:length(channel1)
level=graythresh(channel1{x});
your_mat(:,:,x) = im2bw(channel1{x},level);
end
If you don't want to repeat the loops, you could make it a function.
0 Comments
AJ von Alt
on 24 Jun 2014
You can use cellfun with an anonymous function to get rid of the for loop.
channel1 = { imread('cameraman.tif'),...
rgb2gray(imread('ngc6543a.jpg')),...
rgb2gray(imread('peppers.png')),...
rgb2gray(imread('onion.png')) };
threshfun = @(x) im2bw( x , graythresh(x) );
channelbw = cellfun( threshfun , channel1 , 'UniformOutput', false );
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!