Matlab scalebar


A matlab function to add a scale bar to an image. The scale bar is added by altering image pixel values rather than as an overlay, allowing it to be saved as part of a bitmap. The scale bar can also be labelled, although the text will appear pixelated for small images. There is also an example script which shows basic use of the function.

Download:  scalebar.m   scalebar_example.m


imageOut = scalebar(image, barWidth, barLength, label, [name, value, ...])

image : image to add scalebar to. Either monochrome or colour.

barWidth : width of scale bar in pixels (y dimension in image).

barLength : length of scale bar in pixels (x dimension in image) - this is the distance that provides the 'scale'.

label : text label to place next to the bar. Set as '' for no label.

Optional Name-Pair Values

position : position of scale bar. Allowed values are 'bottom-right' (default), 'top', 'bottom', 'left', 'right',  'top-left', top-right', 'bottom-left' or 'exact'. If 'exact' use barX and barY to specify position.

barX : left position of scale bar in pixels if 'position' is 'exact'.

barY : top position of scale bar in pixels if 'position' is 'exact'.

colour : colour of scale bar, vector of length 3 specifying pixel values in the R, G and B planes. If image is mono then only the R values is used. Default is [255, 255, 255].

textBoxPosition : position of text relative to scale bar. Allowed values are 'bottom' (default), 'top', 'left' or 'right'.

textBoxPadding : space in pixels between text and scale bar. Default is 10.

fontName : font to use for text label. Default is 'Arial'.

fontSize : size of font to use for text label. Default is 15.

fontWeight : 'bold' or 'normal' (default).

fontAngle : 'italic' or 'normal' (default).


% Simple example using default options
image1 = imread(fullfile(matlabroot, '\toolbox\images\imdata\cell.tif'));
image1Labelled = scalebar(image1, 5, 20, '');
figure(1); imagesc(image1Labelled); colormap(gray);

% Example using colour image and different position
image2 = imread(fullfile(matlabroot, '\toolbox\images\imdata\hestain.png'));
image2Labelled = scalebar(image2, 10, 50, '', 'colour', [0 0 0], 'position', 'top-right');
figure(2); imagesc(image2Labelled)

% Example using text label
[image3,map] = imread(fullfile(matlabroot, '\toolbox\images\imdata\m83.tif'));
image3 = uint8(ind2rgb(image3,map) * 255);
image3Labelled = scalebar(image3, 15, 120, '10 kpc', 'fontSize', 25);
figure(3); imagesc(image3Labelled); axis equal;