Display Image with Black Background

The Problem

There are times when an image is created where we don’t do a calculation for part of the image and want to display it black (for example) and not the colormap color which would correspond to zero.

For example, in the image:

original let’s say we are only interested in the block in the center and not the blue background around it.

We can create a background of NaN’s to represent the region which we want to not view, then use the alpha (transparency) channel to enable viewing only of the non-NaN region.

Code

Given a set of data, for example:

[cc lang="matlab"]

%% Create the test image
A = zeros(128,128);
A(33:96,33:96) = repmat( linspace(0, 1, 64), [64 1]);

figure(1),clf;
imagesc( A ); axis(‘off’); axis(‘square’);
colormap(jet);
colorbar;

print -f1 -djpeg original.jpg

%% The better image
B = nan*ones(128,128);
B(33:96,33:96) = repmat( linspace(0, 1, 64), [64 1]);

figure(2),clf;
imagesc( B ); axis(‘off’); axis(‘square’);
colormap(jet);
colorbar;

%% Now set the alpha map for the nan region
z = B;
z(~isnan(B)) = 1;
z(isnan(B)) = 0;

alpha(z);
set(gca, ‘color’, [0 0 0]);

print -f2 -djpeg blocked.jpg

[/cc]

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>