Herr von Wurst
Herr von Wurst

Reputation: 2621

How to get image matrix from axes content

Is there a way to get the content of a contourf plot as an image matrix? I want rasterize only the content, not the axes, labels and the empty space of the entire figure.

My goal is to overlay a transparent, colored contour plot over a grayscale image and I don't see another way, since MATLAB has only one colormap per figure.

Upvotes: 1

Views: 2848

Answers (2)

Bill Cheatham
Bill Cheatham

Reputation: 11917

Not a direct answer to the question, but this is how I think you could achieve your goal:

%# load in grayscale image
gray_im =  rgb2gray(imread('peppers.png'));

%# converting n x m grey image to n x m x 3 rgb gray image
rgb_gray_im = cat( 3, gray_im, gray_im, gray_im );

%# displaying this image
imshow( rgb_gray_im );

%# plotting contourf on top with arbitrary colourmap
hold on
h = axes('position', [0.5, 0.5, 0.2, 0.2]);
z = peaks;
contourf(h, z, [min(z(:)), -6 : 8]);

Which gives the result:

enter image description here

The figure's colourmap is being used for the contourf plot. The background image is not relying on a colourmap, and is instead being displayed in truecolour - i.e. each pixel is being displayed as an RGB value defined in rgb_gray_im.

There are also other ways of getting around the MATLAB colourmap restrictions: see for example this blog post or these answers.

Upvotes: 1

Castilho
Castilho

Reputation: 3187

Try getframe and frame2im

Example from the frame2im documentation:

Create and capture an image using getframe and frame2im:

peaks                      %Make figure
f = getframe;              %Capture screen shot
[im,map] = frame2im(f);    %Return associated image data 
if isempty(map)            %Truecolor system
  rgb = im;
else                       %Indexed system
  rgb = ind2rgb(im,map);   %Convert image data
end

Upvotes: 3

Related Questions