MATLAB Examples

Add Text to Image Data

This example shows how to use array indexing to rasterize text into an existing image.

Draw the text in an axes using the text function. Then, capture the text from the screen using getframe and close the figure.

fig = figure;
t = text(.05,.1,'Mandrill Face','FontSize',20,'FontWeight','bold');
F = getframe(gca,[10 10 200 200]);

Select any plane of the resulting RGB image returned by getframe. Find the pixels that are black (black is 0) and convert their subscripts to indexes using sub2ind. Use these subscripts to "paint" the text into the image contained in the mandrill MAT-file. Use the size of that image, plus the row and column locations of the text to determine the locations in the new image. Index into new image, replacing pixels.

c = F.cdata(:,:,1);
[i,j] = find(c==0);
load mandrill
ind = sub2ind(size(X),i,j);
X(ind) = uint8(255);

Display the new image using the bone colormap.

colormap bone