Pawan Ps
Pawan Ps

Reputation: 31

how to fix these errors in my matlab code?

I'm trying to stack 2D images to get 3D just like How can I plot several 2D image in a stack style in Matlab?

my original code had some errors and someone suggested to go with the below code

M = zeros(25, 50, 8);
for k = 1:8
    img = imread(sprintf('%d-0000.jpg', k + 30));
    img = imresize(img, [25 50]);
    img = im2double(rgb2gray(img));  % Convert to double format
    M(:, :, k) = img;
end
hf2 = figure ;
hs = slice(M,[],[],1:8) ;
shading interp
set(hs,'FaceAlpha',0.8);

this is the expected result How can I plot several 2D image in a stack style in Matlab?

this is the error I get

Error using rgb2gray>parse_inputs (line 81)
MAP must be a m x 3 array.

Error in rgb2gray (line 35)
X = parse_inputs(varargin{:});

Error in stack2 (line 9)
img = im2double(rgb2gray(img)); % Convert to double format

enter image description here

Upvotes: 1

Views: 846

Answers (1)

gnovice
gnovice

Reputation: 125874

Your code as it's written is designed to work with 3-D RGB images. However, the screenshot of your workspace suggests not all of your images fit that criteria. When k is 3, img is a 2-D matrix, meaning that the image in file "33-0000.jpg" is either already a grayscale image or an indexed image for which you didn't load the associated map.

To solve this, you will need to add some additional logic to your loop when loading your image so that you can identify what image type it is and how to properly convert it. Specifically, you need to check the number of dimensions of the image data and whether or not imread returns an associated colormap. Then you can apply rgb2gray or ind2gray as needed. For example:

for k = 1:8
  [img, cmap] = imread(sprintf('%d-0000.jpg', k + 30));
  if ~isempty(cmap)         % There is a colormap, so it's indexed
    img = ind2gray(img, cmap);
  elseif (ndims(img) == 3)  % 3 dimensions, so it's RGB
    img = rgb2gray(img);
  end
  M(:, :, k) = imresize(im2double(img), [25 50]);  % Convert to double and resize
end

Upvotes: 0

Related Questions