MATLAB: Can’t get im2frame working, issues with colormap.

colormapimage processingvideo

Hello,
I have a problem with putting processed images into a movie. I use im2frame to set these images as frames, but I get the following error:
??? Error using ==> im2frame double-precision indexed CData values must be legal colormap indices: 1.0 <= value <= length(colormap)
I've already set the colormap to gray(255), but the error still exists. So probably I'm misinterpreting the error.
Could someone point me out what I'm doing wrong? That would be really great.
Roland
clc
clear all
close all
%Read target folder directory
myFolder = uigetdir('D:\rchoefkens\Bloemen PEP');
if ~isdir(myFolder)
errorMessage = sprintf('Error: The following folder does not exist:\n%s', myFolder);
uiwait(warndlg(errorMessage));
return;
end
filePattern = fullfile(myFolder, 'uvs120424-*.bmp');
imageFiles = dir(filePattern);
%Load and crop backgroundimage
baseFileName = imageFiles(end,:).name;
fullFileName = fullfile(myFolder, baseFileName);
BGin = imread(fullFileName);
BG = imcrop(BGin,[230 300 250 227]);
BGX = rgb2gray(BG);
%Load and process sample images
for k = 1:length(imageFiles)-1
baseFileName1 = imageFiles(k).name;
nF = {k};
numFrames= cell2mat(nF);
fullFileName1 = fullfile(myFolder, baseFileName1);
imageArray = imread(fullFileName1);
%Remove noise and background
Im = imcrop(imageArray,[230 300 250 227]);
I = rgb2gray(Im);
Diff = imabsdiff(I,BGX);
Diff1 = filter2(fspecial('average',8),Diff)/255;
Diff2 = medfilt2(Diff1,[3 3]);
Imench = imadjust(Diff2);
BW = im2bw(Imench,0.12);
BW2 = bwareaopen(BW, 300);
mask = cast(BW2, class(Imench));
img_masked = Imench .* repmat(mask, [1 1 1]);
%Put data in array
array3D{k} = cat(3, img_masked);
end
for L = 1:numFrames
imVis = mat2gray(array3D{L});
map = gray(255);
M(L) = im2frame(imVis,map);
end
implay(M);

Best Answer

See my demo: http://www.mathworks.com/matlabcentral/answers/77594#answer_87271 Here is the relevant snippet. Pay special notice to how I handle colormaps.
% Read the frames back in from disk, and convert them to a movie.
% Preallocate recalledMovie, which will be an array of structures.
% First get a cell array with all the frames.
allTheFrames = cell(numberOfFrames,1);
allTheFrames(:) = {zeros(vidHeight, vidWidth, 3, 'uint8')};
% Next get a cell array with all the colormaps.
allTheColorMaps = cell(numberOfFrames,1);
allTheColorMaps(:) = {zeros(256, 3)};
% Now combine these to make the array of structures.
recalledMovie = struct('cdata', allTheFrames, 'colormap', allTheColorMaps)
for frame = 1 : numberOfFrames
% Construct an output image file name.
outputBaseFileName = sprintf('Frame %4.4d.png', frame);
outputFullFileName = fullfile(outputFolder, outputBaseFileName);
% Read the image in from disk.
thisFrame = imread(outputFullFileName);
% Convert the image into a "movie frame" structure.
recalledMovie(frame) = im2frame(thisFrame);
end
Related Question