1
votes

I'm looking to load image files into Mat lab and save them all to an animated .GIF of a set speed. i have tried loading them in using imread() and mapping them with rgb2ind() then saving with the given imwrite() code from the website appending them to the file, i have errors when trying to use the rgb2ind() saying that i need a uint8 array or a 3Duint8 array when i try various things.

%arg 1 number of inputs
%arg 2 is speed
%arg[] files
function main(varargin)

num = str2num(varargin{1});
speed = str2double(varargin{2});

for i=1:num
a = imread(varargin{i+2});
[A map] = rgb2ind(a,256);
if i==1
   imwrite(A,map,'new.gif', 'gif','LoopCount',65535,'DelayTime',speed)
else
    imwrite(A,map,'new.gif', 'gif','WriteMode','append','DelayTime',speed)

end

end
1
I posted an answer based on an assumption that a = imread(varargin{i+2}); reads a Grayscale image. If this is not the case, please let me know (there is also a chance that your input images are [colored] indexed images, and your are not using imread correctly). - Rotem

1 Answers

0
votes

It's most likely that you are passing Grayscale as input image to rgb2ind.

Example for correct usage:

I = imread('peppers.png');
[A, map] = rgb2ind(I, 256);

Above sample loads image in RGB format and there is no error (peppers.png is RGB image).

Example that gives and error message:

I = imread('cameraman.tif');
[A, map] = rgb2ind(I, 256);

Result of above code:

Error using cq
First input must be a 3-D uint8 array.

Error in rgb2ind (line 93)
[map,X] = matlab.images.internal.cq(RGB,m);

The reason for the error is that cameraman.tif is a Grayscale image (and not RGB).

A quick fix is to convert Grayscale images to RGB format.
Converting Grayscale to RGB is done by duplicating the Grayscale three times (creating an RGB image with R=G=B for all pixels).

Here is a code sample that checks if image is in Grayscale format, and convert to RGB if needed:

I = imread('cameraman.tif');

%Check if I is Grayscale
if (size(I, 3) == 1)
    %Convert Grayscale to RGB by duplicating I three times.
    I = cat(3, I, I, I);
end

[A, map] = rgb2ind(I, 256);

The above code is executed successfully.