Matlab: Scalebars

From Course Wiki
Revision as of 22:58, 22 February 2015 by Steven Nagle (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
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.

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;

% read in the image and display
if ischar(imageName)
    image1 = imread(imageName);
    image1 = imageName;
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 tone as requested
if negative