Matlab: Scalebars

From Course Wiki
Jump to: navigation, search
20.309: Biological Instrumentation and Measurement

ImageBar 774.jpg


The code shown below can be used to add a scalebar to any image. Take care to ensure that the left edge of the scale bar is not off the left edge of the image. Otherwise it is up to you to decide how large, and in what units, the scalebar should be. Regarding size, your instructors suggest some modest multiple of the most characteristic object size in the image, such as a cell or bead.

The program returns a handle to the figure containing the image. You can then save that figure or print to a file. This is not ideal because it adds a border, just like in the figure. It would be better to save the image data only, with the scalar overlaid. Unfortunately the getimage command in Matlab does not retain the rectangle or text data, so we (or you) will have to be more clever.

function hImage = scalebar(imageName, pixelSize, magnification, barScale, units, negative)
% SCALEBAR(imageFile, pixelSize, pixelSize, magnification, units, negative)
%   Adds a scale bar in the lower right-hand corner of an image in the 
%   active set of axes. Be sure that your whole scale bar fits within the
%   image width (minus 10%). It should not touch the left edge of your
%   image.
%
%   Required inputs are:
%      imageName             : EITHER an image variable name (e.g. foo)
%                              OR a file path and filename (e.g. ~/foo.png)
%      pixelSize (float)     : the actual size of a camera pixel (e.g. 7.4)
%      magnification (float) : the microscope magnification (e.g. 40)
%      barScale (float)      : bar size in image units (e.g. 100)
%      units (string)        : the units of the image (e.g. micron)
%
%   Optional input:
%      negative (int)        : white tone or black (e.g. 1)
%
%   SFNagle 2015 v1

if nargin < 6
    negative = 1;
end

% read in the image and display
if ischar(imageName)
    image1 = imread(imageName);
else
    image1 = imageName;
end
hImage = imshow(image1);

% plot a scale bar in black first
scaleBarWidth = floor( 1/(pixelSize/magnification) * barScale);
scaleBarHeight = 7;
xPos = size(image1,2)*0.9 - scaleBarWidth;
yPos = size(image1,1)*0.9 - scaleBarHeight;
textCenterX = xPos + floor(scaleBarWidth/2);
textCenterY = yPos + scaleBarHeight*5;
rectPosition = [xPos, yPos, scaleBarWidth, scaleBarHeight];
hRect = rectangle('Position', rectPosition);

% label the scale bar
str = sprintf(['%4d ' units], barScale);
hText = text(textCenterX,textCenterY,str);
set(hText,'HorizontalAlignment','center');

% set tone as requested
if negative
    set(hRect,'EdgeColor','w');
    set(hRect,'FaceColor','w');
    set(hText,'Color','w');
else
    set(hRect,'EdgeColor','k');
    set(hRect,'FaceColor','k');
    set(hText,'Color','k');
end