You are on page 1of 327

DigitalMicrograph

2.1.1
Copyright 2012 Gatan Inc. All Rights Reserved.

DigitalMicrograph 2.1.1
Copyright 2012 Gatan Inc. All Rights Reserved.
All rights reserved. No parts of this work may be reproduced in any form or by any means - graphic, electronic, or
mechanical, including photocopying, recording, taping, or information storage and retrieval systems - without the
written permission of the publisher.
Products that are referred to in this document may be either trademarks and/or registered trademarks of the
respective owners. The publisher and the author make no claim to these trademarks.
While every precaution has been taken in the preparation of this document, the publisher and the author assume no
responsibility for errors or omissions, or for damages resulting from the use of information contained in this
document or from the use of programs and source code that may accompany it. In no event shall the publisher and
the author be liable for any loss of profit or any other commercial damage caused or alleged to have been caused
directly or indirectly by this document.

Publisher
Gatan Inc.
Technical Editors
Gatan Software Team

http:www.gatan.com

Gatan Inc.
5794 W. Las Positas Blvd.
Pleasanton, California USA
925-463-0200

Contents

Table of Contents
Foreword

Part I Digital Micrograph

1 Overview
................................................................................................................................... 1
The DigitalMicrograph
..........................................................................................................................................................
Process
2
Basic Concepts.......................................................................................................................................................... 3

2 Basic Procedures
................................................................................................................................... 3
DigitalMicrograph
..........................................................................................................................................................
Environm ent
4
Creating Im age..........................................................................................................................................................
Docum ents
6
Using Im age Window
..........................................................................................................................................................
s
8
Saving Im age Docum
..........................................................................................................................................................
ents
9
Printing Im age..........................................................................................................................................................
Docum ents
15
Closing Im age..........................................................................................................................................................
Docum ents
16
Using Text Window
..........................................................................................................................................................
s
16
Using Floating..........................................................................................................................................................
Palettes
17
Setting Preferences
.......................................................................................................................................................... 19
Session Inform
..........................................................................................................................................................
ation
22
Im porting Im ages
.......................................................................................................................................................... 27
Databar
.......................................................................................................................................................... 29

3 Image...................................................................................................................................
Display
31
About Im age Displays
.......................................................................................................................................................... 32
About Contrast
.........................................................................................................................................................
Limits
34
About Contrast
.........................................................................................................................................................
Transformations
39
About Lookup
.........................................................................................................................................................
Tables
42
Using Raster Im
..........................................................................................................................................................
age Displays
43
Using Surface..........................................................................................................................................................
Plot Im age Displays
44
Using RGB Im age
..........................................................................................................................................................
Displays
45
Using Line Plot
..........................................................................................................................................................
Im age Displays
45
Using Line Plot
..........................................................................................................................................................
Legends
52
Using Speadsheet
..........................................................................................................................................................
Im age Displays
55
Using Im age Displays
..........................................................................................................................................................
w ith Com plex Data
55

4 Image...................................................................................................................................
Documents
56
Manipulating Annotations
.......................................................................................................................................................... 57
Editing Annotations
.......................................................................................................................................................... 61
About Targets.......................................................................................................................................................... 62
Setting Object..........................................................................................................................................................
Inform ation
63
Annotations .......................................................................................................................................................... 64

5 Image...................................................................................................................................
Processing and Analysis
68
Using Regions..........................................................................................................................................................
of Interest
68
Using Line Profiles
.......................................................................................................................................................... 73
Using Calibrations
.......................................................................................................................................................... 74
Using the Slice
..........................................................................................................................................................
Tool
76
Im age Processing
.......................................................................................................................................................... 77
Changing Data
.........................................................................................................................................................
Types
77
Using Image
.........................................................................................................................................................
Transformations
80
Using Filtering
......................................................................................................................................................... 82
Using Convolutions
......................................................................................................................................................... 86
Using Simple
.........................................................................................................................................................
Math
88
Copyright 2012 Gatan Inc. All Rights Reserved.

II

DigitalMicrograph
Fourier Processing
.......................................................................................................................................................... 89
Using Fourier
.........................................................................................................................................................
Transforms
90
Auto-Correlations
......................................................................................................................................................... 91
Cross-Correlations
......................................................................................................................................................... 92
Using Fourier
.........................................................................................................................................................
Masking
93
Im age Analysis
.......................................................................................................................................................... 97
Calculating.........................................................................................................................................................
Image Statistics
97
Using Histograms
......................................................................................................................................................... 97
Particle Analysis
......................................................................................................................................................... 98
Image Preparation......................................................................................................................................... 98
Thresholding
......................................................................................................................................... 99
Finding Particles......................................................................................................................................... 100
Analyzing Particles
......................................................................................................................................... 102

6 Images
................................................................................................................................... 103
Setting Im age
..........................................................................................................................................................
Inform ation
107

7 Reference
................................................................................................................................... 109
Toolbars
.......................................................................................................................................................... 109
File Tools ......................................................................................................................................................... 109
Standard .........................................................................................................................................................
Tools
110
Line Plot Tools
......................................................................................................................................................... 111
ROI Tools......................................................................................................................................................... 112
Masking Tools
......................................................................................................................................................... 112
Floating Palettes
.......................................................................................................................................................... 113
Histogram......................................................................................................................................................... 113
Display Control
......................................................................................................................................................... 113
Image Status
......................................................................................................................................................... 114
Target ......................................................................................................................................................... 115
Control ......................................................................................................................................................... 115
Slice
......................................................................................................................................................... 116
Progress ......................................................................................................................................................... 116
Acquisition
.........................................................................................................................................................
Status
116
Shortcuts .......................................................................................................................................................... 117

8 Scripting
................................................................................................................................... 118
Types and Variables
.......................................................................................................................................................... 127
Expressions.......................................................................................................................................................... 129
Statem ents .......................................................................................................................................................... 136
Functions .......................................................................................................................................................... 142
Objects
.......................................................................................................................................................... 146
Threading......................................................................................................................................................... 157
Event Handling
......................................................................................................................................................... 168
TagGroup.........................................................................................................................................................
Object
171
Menus ......................................................................................................................................................... 192
String Object
......................................................................................................................................................... 200
Document.........................................................................................................................................................
Object Model
203
Window Object ......................................................................................................................................... 203
Dialogs
......................................................................................................................................... 207
ImageDocument.........................................................................................................................................
Object
231
Image Object ......................................................................................................................................... 240
Component Object
......................................................................................................................................... 253
ImageDisplay Object
......................................................................................................................................... 261
RasterImageDisplay
.........................................................................................................................................
Object
269
SurfacePlotImageDisplay
.........................................................................................................................................
Object
271
LinePlotImageDisplay
.........................................................................................................................................
Object
273
Copyright 2012 Gatan Inc. All Rights Reserved.

Contents

III

ROI Object
......................................................................................................................................... 277
Im age Operations
.......................................................................................................................................................... 284
Packages .......................................................................................................................................................... 291
File Input and..........................................................................................................................................................
Output
291
Utility Functions
.......................................................................................................................................................... 299
Exam ple Scripts
.......................................................................................................................................................... 302
Tag Types......................................................................................................................................................... 302
Reference .......................................................................................................................................................... 305
Script Functions
.........................................................................................................................................................
By Category
305

Index

321

Copyright 2012 Gatan Inc. All Rights Reserved.

III

DigitalMicrograph

Digital Micrograph
by Gatan, Inc.

1.1

Overview

DigitalMicrograph
DigitalMicrograph is an application used for acquiring, visualizing, analyzing, and
processing digital image data, primarily within the context of electron microscopy. It can be
thought of as an environment that can be enhanced with different attachments (plug-ins) to
perform a variety of analytical tasks.
How does the DigitalMicrograph process work? With DigitalMicrograph and one of the
acquisition units, such as a CCD camera, you can acquire a digital image of a sample,
manipulate its display, analyze, process, print, and archive it for long-term storage.

Full image-acquisition power


DigitalMicrograph provides the capability, through the use of plug-in extensions to the
application, to control and acquire images and data from CCD cameras, EELS systems,
imaging filters, and a variety of other sources.

Visualization, processing, and analysis algorithms


DigitalMicrograph gives you many different ways to view your data and images. It also
provides you with a full complement of image processing algorithms and analysis techniques
for coming to grips with the information contained within your data.

Flexible page design and presentation


Presentation of your data in DigitalMicrograph is easy and flexible. You can collect many
images onto a single page, size them the way you want relative to the page, arrange them
within the page, and print them.

Extensive storage options


DigitalMicrograph supports all of the top industry standards for storing files. You can open and
store TIFF, GIF, PICT, BMP, and other formats using DigitalMicrograph.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

1.1.1

The DigitalMicrograph Process

The DigitalMicrograph Process


DigitalMicrograph eliminates many of the steps you perform when using film, but acquiring an
image within DigitalMicrograph is still analogous to obtaining an image on film.
A simple configuration would be an electron microscope with a CCD camera (imaging
device) interfaced to a computer.
With this configuration, an image is formed by the microscope on the CCD detector. It is
digitized and read out by the Camera Controller where it is converted to a form that the
computer can read. The Camera Controller sends the data to the computer. This connection
can be via FireWire or through a proprietary PCI card in the computer. After the data is
transferred to the computer's memory, DigitalMicrograph can access it.
A DigitalMicrograph session would typically follow a procedure similar to the following:

1. Acquire your data.


DigitalMicrograph allows you to acquire data from many different sources such
as CCD cameras, EELS systems, or imaging filters. Your data may be an
image, a spectrum, or something totally different. You may be analyzing data
that already exists in a file. Acquisition would then consist of simply loading the
file into DigitalMicrograph.

2. Visualize your data.


DigitalMicrograph can display data and images in many ways. You can display
images in a format similar to a photograph, as a surface plot, as a numerical
spreadsheet display, or as a one-dimensional line plot.

3. Analyze your data.


You can measure areas and lengths, perform various statistical and
mathematical calculations, and analyze particles present in your image.

4. Process your data.


You can enhance your image by performing Fourier filtering, sharpening, or
other types of image processing.

5. Present your data.


The most important result of the entire process is the presentation of your
data. You can arrange multiple images on a page and annotate your images
and page through the use of text, lines, boxes, ovals, or clip-art imported from
other applications.

Copyright 2012 Gatan Inc. All Rights Reserved.

DigitalMicrograph

DigitalMicrograph makes it easy to arrange multiple images and other


annotations on a page to produce the layout you desire.

6. Archive your data.


At each part of this process, you should be saving your data to disk. The
beauty of digital processing is that if you do this at each step of the process,
you can always return to a previous step and try again.
In the end, however, you will want to save your data to a long-term storage
medium where it can be found and retrieved in the future. DigitalMicrograph
gives you many choices and formats for saving data to disk. It also integrates
with archiving applications to keep track of the images that you acquire and
generate.

1.1.2

Basic Concepts

Basic Concepts
DigitalMicrograph presents all of its information through the use of windows. Each window
contains a set of related information.
Image document windows contain a visible representation of a page of paper. Images can be
placed on this page. Other objects such as lines, boxes, and text can also be placed on this
page. You can open, save, and print image document windows.
Many aspects of images and objects placed on pages can be controlled through the use of
palettes. Palettes "float" above image document and text document windows. You cannot
open, save, or print palettes. Palettes can be recognized by their small title bar.
Text document windows contain text. Text document windows do not hold any other
graphical objects. You can open, save, and print text document windows.
DigitalMicrograph can be extended to support acquisition devices through the use of plug-ins.
Plug-ins are placed in a folder named "PlugIns".
DigitalMicrograph can also run simple programs (called scripts) which carry out automated
tasks.

1.2

Basic Procedures
Basic Procedures
DigitalMicrograph lets you acquire, process, analyze, and present your images through its
easy-to-use commands and tools. Once you master the basics of using DigitalMicrograph,
you will want to learn more about the application and add more skills to your arsenal. This
chapter assumes you are familiar with the basic ideas of the mouse, manipulating windows
and menus, and launching applications on your computer. If you are not, please refer to the
manual that came with your computer.
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

The DigitalMicrograph Workplace


DigitalMicrograph displays images within image windows. There are other types of windows
(called palettes) that allow you to manipulate details of those images and other objects. Still
other types of windows give you information about an image or the results of analysis or
processing algorithms. .
Image windows can display images one at a time (image mode) or more than one at a time
(page mode). When the image window is in image mode, the image is the main focus of the
window. The image will resize when you change the size of the window and any operations
you perform will take place on the image. When the image window is in page mode, a page
will be displayed and multiple images can be laid out on the page. Operations involving
images will apply to the image that is selected on the page. You can switch between image
mode and page mode using the Target floating palette.
Note: Since an image window can display either a single image or a page containing zero or
more images, we will refer to the contents of the image window as an image document. The
image document term will be taken to mean zero or more images laid out on a page and
viewed either as a page or as a single view of one of the images.

Window settings can suit your preferences


Individual windows and palettes in DigitalMicrograph can be adjusted in several ways to suit
your preferences. You can zoom in or out to view more or less detail in your window, resize
the window, and more. You can also adjust the floating palettes, tools, and other gadgets to
suit your needs. Using the Layout Manager you can save different set-ups of your floating
windows for easy recall.

Saving documents to be secure


If you have worked with a computer, you already know the importance of saving your work
often. Saving your image documents frequently avoids the pain of losing a day's work when
the power fails unexpectedly. Saved image documents also give you a record of your
progress and a place to restart from if an experimental processing algorithm does not
produce the results you desire.

1.2.1

DigitalMicrograph Environment

The DigitalMicrograph environment


Before you can use DigitalMicrograph, you must install it on your computer according to the
instructions contained in the Installing DigitalMicrograph manual.

To start DigitalMicrograph
You launch DigitalMicrograph as you would any other application.

Copyright 2012 Gatan Inc. All Rights Reserved.

DigitalMicrograph

Select DigitalMicrograph from the Start menu, or


Double click the DigitalMicrograph icon on the desktop.
By choosing commands from the menu bar, you can now create a new image
window, open an existing one, or acquire one from an acquisition device.

The DigitalMicrograph environment


When opening DigitalMicrograph you will see the following window

This screenshot shows DigitalMicrograph with only its basic plug-ins displayed. Actual
installation will have more plug-ins installed, which means that more menu items may
appear. Also the number of other windows can be different.

Key areas

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

Menu bar
At the top is the menu bar containing the File, Edit, Display, Process, Analysis,
Window, Microscope and Help menus. In these menus are all the controls for
operating the application.
Tool bar
Under the menu bar is a toolbar. In this screenshot the File Tools, Standard
Tools and ROI tools are displayed. Other toolbars are available.
Floating Windows
On the left hand side several Floating Windows are displayed. In this
screenshot the basic set is shown: Histogram, Image Status, Target and
Display Control. Floating Windows can also appear on the right hand side of
the screen.
Result Window
At the bottom is the Results Window. This window is used to report results
and updates of operations performed by DigitalMicrograph.
Image Windows
All images are displayed in Image Windows. They can be displayed anywhere
in the application, and many images can be open at the same time.

To exit DigitalMicrograph
You can exit DigitalMicrograph when you're finished with it.
Choose Exit from the File menu, or
Hold down the Alt key and hit F4 to exit.
If any modified documents are open and haven't been saved, DigitalMicrograph asks
whether you want to save the documents.
You can exit without saving any of the files.
Hold down Control and Alt keys and hit F4 to exit.

1.2.2

Creating Image Documents

Creating/Opening Image Documents


After you have launched DigitalMicrograph, you begin to work with an image by either
acquiring a new one from an acquisition device such as a camera, creating a new one, or
opening an existing one.

To acquire a new image


You can acquire an image with an acquisition device such as a CCD camera, EELS
Copyright 2012 Gatan Inc. All Rights Reserved.

DigitalMicrograph

system, DigiScan, or imaging filter.


To acquire from an external device, use the plug-in supplied with the device. For
example, the software supplied with a CCD camera will present you with a floating
command palette through which you can control the camera. See the manual
provided with your acquisition device for specific details on acquiring an image.
Any images you acquire will automatically appear in image mode.

To create a new image manually


You can create a new image manually.
1. Choose New from the File menu.
2. Click on the Image tab at the top of the dialog.
3. Enter a name for the image window which will contain the new image.
4. Enter a width and height for the image.
You can choose a width and height of 200 x 200 for experimental purposes.
5. Change the display type to "Raster."
This indicates that the image will be displayed in a format similar to a
photograph.
6. Change the data type to "Real" with "4 bytes."
This generates an image that can hold real numbers (as opposed to integers,
or complex numbers).
7. Select a pattern and click OK.
This operation will actually create an image document with a single image and
display that image document in image mode.

To open an image from disk


You can open an existing DigitalMicrograph image document or you can open images
created in other applications and saved in formats DigitalMicrograph understands,
such as TIFF, GIF, BMP and JPEG.
1. Choose Open from the File menu, or click the
Tools" Toolbar.

button on the "File

2. Select the image document or image you want to open.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

3. Click Open.
The image will open immediately.
DigitalMicrograph will alert you if it does not recognize the file type.
In order to open images that are not in the Gatan DigitalMicrograph file format, the
"Import/Export Plug-in" (which is shipped with DigitalMicrograph) should be in the
Plugins folder.

To create an empty image document


You can create an empty image document that will be displayed in page mode on
which you can place images from other windows.
1. Choose New from the File menu.
2. Click on the Document tab at the top of the dialog.
3. Enter a name for the image document.
4. Click OK.
An empty image document will be displayed in page mode. You will see a
representation of the page in the window.

1.2.3

Using Image Windows

Using Image Windows


DigitalMicrograph provides several ways to customize an image window. Among other things,
you can magnify your view of the document, change the page size, and move the image and
page around within the window.

To resize the window


Resize the window as you would resize any window on your operating system.
To resize manually, click and drag an edge of the window.
If the image document is currently in image mode, its image will change from
one integer multiple of its true size to another as you drag the window border.
If you hold down the Alt key as you drag the window border then the image will
resize to the largest size that fits in the window. If you hold down the Control
key as you drag the window border then the image will not resize.
If the image document is currently being viewed in page mode, the page will
always be sized to fit as large as possible within the window.

Copyright 2012 Gatan Inc. All Rights Reserved.

DigitalMicrograph

To resize around either the image or the page, click in the maximize box.
Re-sizing around an image or page will size the window so that the image or
page fits exactly within the window at its current resolution.

To change printed page size or orientation


You can change the size or orientation of the page.
Select Page Setup from the File menu.
Enter the desired size and orientation in the dialog that is presented.

To change the magnification of the image document


You can change the size at which DigitalMicrograph displays the image or the page
within the window.
Click in the image window with the Zoom tool (

) from the Standard Tools.

The Zoom tool will display a "+" inside the magnifying glass to indicate you will
be magnifying around the point at which you click.
Hold down the Alt key to demagnify. The Magnify Page tool will display a "-"
inside the magnifying glass to indicate you will be demagnifying.
You can also you the mouse wheel to zoom in and out around the location of
the image where the mouse is located.

To move the image around within the window (page mode only)
You can move the image within the window.
Click and drag the image within the image document with the Pointer tool.

To move the page around within the window


You can move the page within the window.
Click and drag the page within the image document with the Move Page tool (a.k.a
Hand Tool, see Standard Tools).

1.2.4

Saving Image Documents

Saving an Image Document


As you work, save early and often; don't wait until you finish working or until "later." This will
prevent you from losing images due to power failures and other unexpected circumstances.
The File menu contains 4 items related to saving images: Save, Save As..., Save Numbered,
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

10

and Save Display As... With the Save and the Save As items you can save the image data;
with the Save Display As item you can save the screen rendering of your image document,
and with Save Numbered you can do either depending on the preferences you have supplied.
The same functions can also be accessed from the FileTools toolbar:

Note that the saving behavior has changed considerably from that in GMS 1.2 and all
earlier versions of GMS and DM.
The different image formats supported in DigitalMicrograph have different capabilities.
This means that at some times you may be presented with more format choices than
at other times. And sometimes the system has to ask for clarification on how to deal
with limitations of a particular format.
The Gatan file format is the only format that can save all information properly at all
times, and is the only choice when you are saving an image document that is
displayed in page mode.

To save an image document in the Gatan file format


You can save your image document to disk at any time.
Choose Save from the File menu to save current image or click the Save button (
in the File Tools.

If this is the first time you've saved the file, DigitalMicrograph displays the Save
As dialog box. Type in name for the file, choose the desired directory, choose
"Gatan Format (*.dm3)", and click Save.
If the image document has already been saved once or was loaded from a file,
DigitalMicrograph saves it to the same file, overwriting the previous version.
Choose Save As from the File menu to save to a new file.
DigitalMicrograph displays the Save As dialog box. Type a name for the file,
choose the desired directory, and click Save.

To save an image in TIFF format


If your image is not displayed in page mode you can save your image in other formats
than just Gatan Format. The most important of those formats is TIFF. However TIFF
Copyright 2012 Gatan Inc. All Rights Reserved.

11

DigitalMicrograph

has certain limitations, and other applications implement different levels of TIFF
format. For example Adobe PhotoShop does not cope well with negative values
stored in images stored as signed 2-byte integer format - it assumes that they are
large and positive. This is the format generated by Gatan's MSC cameras. When
trying to save an MSC image with scale marker to TIFF the following will happen:
Choose Save from the File menu to save current image or click the Save button (
in the File Tools.

Choose TIFF from the "Save as type" drop list.


The following warning dialog will appear:

This dialog appears because your image contains an annotation (the scale
marker) and TIFF can not handle annotations as separate objects. So you are
given a choice to burn the annotation into the image data, or to ignore the
annotation. (Contrast limits and Survey limits can be slightly different and are
discussed elsewhere. Most of the time it doesn't matter very much which one
you choose.)
Hit the OK button.
Now the following warning dialog appears:

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

12

DigitalMicrograph gives you a choice to convert to 16 bit unsigned so that you


can more readily interpret the data in Adobe PhotoShop. Converting to 16 bit
unsigned is done by adding 32768 to all image values.
Hit the OK button.
The image will now be saved using the preferences you supplied. Note that
you can lock in your choices on the warning dialogs by checking the
appropriate check boxes, so that you do not have to go through this whole
procedure each time.
Note that even though the image you just saved can be opened in Adobe PhotoShop,
it may initially look really boring, probably very grayish with very little contrast. This is
because PhotoShop assumes the contrast limits to correspond to the full dynamic
range of the data format, so for 2 byte data it displays by default intensity 0 as black
and intensity 65535 as white. Go to the Image menu, Adjust -> Levels to fix the display
(Adjust->Auto Levels may work better).
To maintain compatibility with the largest number of other applications use the Save
Display As function in DigitalMicrograph.
If you have problems with other applications, note that you can always load the TIFF
image back into DigitalMicrograph and you will get all image data and meta data back.
Then try to save in some other format to make the data appear properly in the other
application

To save an image in TIFF format using Save Display As...


1. Select the image you want to save and select Save Display As... from the file menu
or click the Save Display button ( ) in the File Tools.
The standard Save As dialog will be displayed and you can now choose from
another list of file formats, including GIF and JPEG. In this example choose
TIFF and pick a name and location for the image.
2. Hit the Save button.
Copyright 2012 Gatan Inc. All Rights Reserved.

13

DigitalMicrograph

The following dialog will appear:

Here you choose whether to save the image in the size displayed on the
screen, or in its full resolution. And you can choose to include the annotations.
Once again you can lock in on your choices so that you do not have to see this
dialog each time you save an image.
3. Hit the OK button.
The image will now be saved.
When you open this image in Adobe PhotoShop, you will see exactly the same
thing as in DigitalMicrograph.

To save a series of images


DigitalMicrograph can save image documents in a series of files so that each time
you save, the image document gets a new filename.
Choose Save Numbered from the File menu or click the Save Numbered button (
in the File Tools.

You can set the directory in which to save the image documents, the name of
the series, and the number in the series that you want to begin with (see "
Setting Preferences").
For example, the first time you do this the image document will be saved with the
name "Image Series.1." The next time you do it, the image will be saved with the
name "Image Series.2."

Batch Convert
Using the Batch Convert... menu item images saved in Gatan Format can be
converted to different data formats. This procedure will always save the data or

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

14

display at the resolution of the source data, and it will include the annotations in the
result. If the Gatan file contained an image document with more than one image, only
one of the images is exported and a message to this effect is printed to the results
window.
1. Choose Batch Convert from the File menu
The following dialog will appear

In this dialog you can enter the folder name by either typing it (make sure to
use back slashes as in the screen shot) or using the Browse... button. If you
want to convert all files in sub-folders of the selected folder as well, then check
the Convert sub-folders button.
2. Next choose to either save the image data in "Data Only" or MRC format, or save
the image display in BMP, JPEG or TIFF format. MRC format does not support all
data formats and if an image is encountered that can not be converted to MRC a
message will be printed to the results window.
3. Hit the OK button.
The procedure will now start converting all files in the selected folder and the
following progress window is shown.

Copyright 2012 Gatan Inc. All Rights Reserved.

15

DigitalMicrograph

Hit the Cancel button to abort the procedure.

1.2.5

Printing Image Documents

Printing Image Documents


Image documents can be viewed in image mode or page mode. Freshly acquired images are
set to image mode. When you print these images without doing any page layout, they are
printed such that they are centered at the top of the page and fill about 90% of the printable
area of the page.
To exercise more control over the placement of the image or to add multiple images to the
document, switch to page mode and lay out the image(s) as you desire. After you have laid
out the image(s) in page mode, whenever you print (even if the image document is being
viewed in image mode), DigitalMicrograph will use the page layout that you specified.

To select your printer and printing options


The method of selecting your printer and printing options depends on the operating
system software that you are using. Generally you use the Printers panel in Settings
under the Start Menu.
Once you have a printer selected, you can set the specific options for that printer.
Choose Page Setup under the File menu to set page size, orientation, and other
options.
DigitalMicrograph will remember your page size, orientation, and other settings
when you save your file in DigitalMicrograph file format.

To print an image document


Printing speed depends on the complexity of your document. Generally, the more
images contained in your image window, the longer it will take to print. Also the
resolution of the images in your document will affect the print speed.
1. Choose Print from the File menu or click the Print button (

) in the File Tools.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

16

2. Select your desired print options.


Print options include the printer to use and how many pages to print on each
sheet of paper. See the manual that came with your computer or printer for
more information.
3. Type in the number of copies in the Copies text box.
4. Click OK.

1.2.6

Closing Image Documents

Closing Image Documents


When you're finished using an image document, you can close it to remove the image from
your computer's memory. When you're finished using DigitalMicrograph, you can exit it to end
the current session. When you close image documents or exit DigitalMicrograph, you will be
asked if you want to save any of the changes.

To close an image document


You can close image documents when you're finished with them to save on memory.
Choose Close from the File menu or click in the Close box.
Hold down the Alt key while closing the window to tell DigitalMicrograph not to
present the dialog asking whether to save the file or not.
Hold down the Shift and Alt keys to close all windows and avoid being
prompted to save each one.

1.2.7

Using Text Windows

Using Text Windows


In addition to image windows, DigitalMicrograph uses text windows to contain scripts and
output from algorithms. Text windows are also used to write scripts to perform tasks within
DigitalMicrograph.
You can cut, copy, and paste text within text windows. You can also drag text between text
windows and image windows. Finally, you can load and save text windows used for scripting.
The Results window, a special text window, keeps a running log of information from
processing, analysis, acquisition, and other parts of DigitalMicrograph. You can save it to a
text file. If you move or resize the Results window, DigitalMicrograph will remember whether it
is open and where it is the next time you launch DigitalMicrograph.

To open the Results window

Copyright 2012 Gatan Inc. All Rights Reserved.

17

DigitalMicrograph

The Results window stores results from processing, analysis, and other aspects of
DigitalMicrograph.
Choose Open Results from the Window menu.

1.2.8

Using Floating Palettes

Using Floating Windows


Floating windows are used to display information about and directly manipulate images and
other objects within image documents.
You can arrange floating windows in a configuration that most suits your requirements. You
can group sets of the floating windows together and you can "roll-up" a particular floating
window in order to reduce the space it takes on the screen.
Some of the older DigitalMicrograph acquisition plug-ins will present a floating window that
cannot be grouped with other floating windows.
DigitalMicrograph will remember the positions and groupings of all of your floating windows
from session to session. If you exit DigitalMicrograph and launch it again later, the floating
windows and groups will return to the same configuration.

To open a new floating window


DigitalMicrograph lists all of the floating windows in the Floating Windows menu.
Select the desired floating window from the Floating Windows submenu under the
Window menu.
DigitalMicrograph will add the new floating window to the group at the top-left of
the main screen. If no group exists there, DigitalMicrograph will create a new
group.

To move floating windows


Floating windows can be moved in the following ways:
Move an entire group of floating windows.
Grab the group title bar and drag it to a new location.
Move a floating window above another within a group.
Grab the title bar of a floating window and drag and drop it on the title bar of
another to place it above the existing window.
Move a floating window below another within a group.
Grab the title bar of a floating window and drag and drop it on the contents of
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

18

another to place it below the existing window.


Move a floating window to another group.
Grab the title bar of a floating window and drag it to the new group.
Move a floating window to a new group.
Grab the title bar of a floating window and drop it somewhere where there is no
other floating window.

To roll up or roll down a floating window


DigitalMicrograph allows you to roll up and roll down floating windows to save screen
space and get unused controls out of your way.
Click on the Twist Down control to roll up or roll down a floating window.

To close a floating window


You can close floating palettes completely.
Close an entire group of floating windows.
Click in the Close box of the group palette.
Close a specific floating windows.
Drag the floating window to a new group and close the new group.

Floating Windows Layout Manager


In many cases there are too many floating windows that you want to display simultaneously,
and you are forced to open and close the relevant ones. To alleviate this problem there is a
"Floating Windows Layout Manager". With this feature, you can easily save and retrieve
different configurations of Floating Windows.
For example you can set up a layout called "Acquisition" that includes all panels you need
during acquisition, and a layout called "Analysis" that includes post-processing and analysis
related panels.
All this functionality is located in the Windows menu under the "Layout Manager" sub-menu:

The "Save Layout As" item allows you to save your current layout and give it a name.
Copyright 2012 Gatan Inc. All Rights Reserved.

19

DigitalMicrograph

When choosing "Manage Layouts" a dialog is displayed that allows you to rename and
delete existing layouts.
The items under the separator are the actual layouts you have saved. Choosing one of those
items forces all floating windows to be redrawn as defined by that layout.

1.2.9

Setting Preferences

Setting Preferences and Information


Preferences help DigitalMicrograph to tailor its operation to your specific needs.
The Global Info dialog allows you to choose preferences. This dialog is divided into a list of
panels along the left side, and the selected panel on the right side. To switch to a different
panel, select a different panel from the list on the left.

To enter Data Bar preferences


DigitalMicrograph can automatically add a scale marker and other information to
images that you acquire from acquisition devices.
1. Choose Global Info from the File menu or click the Preferences button (
File Tools.

) in the

The Global Info dialog will appear.


2. Select Data Bar on the left side of the dialog box.
The Data Bar panel will appear in the right side of the dialog box.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

20

3. Enter the information in the right portion of the dialog box.


Check the check box "Add Scale Marker After Acquisition" if you want a scale
marker automatically placed on your acquired images.
All other preferences in this panel are related to the Data Bar. This topic is
discussed elsewhere.
4. Click OK.
Switching to a different panel will automatically save your choices.

To enter Save Numbered preferences


DigitalMicrograph can automatically save a series of images to a sequentially
numbered set of files. This is useful during acquisition or during a long processing
sequence.
1. Choose Global Info from the File menu or click the Preferences button (
File Tools.
The Global Info dialog will appear.
2. Select Save Numbered on the left side of the dialog box.

Copyright 2012 Gatan Inc. All Rights Reserved.

) in the

21

DigitalMicrograph

The Save Numbered panel will appear in the right side of the dialog box.

3. Enter the information in the right portion of the dialog box.


You can specify in this panel what the name of the images should be, where
they should be located and what format they should be saved in.
4. Click OK.
Switching to a different panel will automatically save your choices.

To enter page measurement unit preferences


DigitalMicrograph can display image measurements in English or metric units.
1. Choose Global Info from the File menu or click the Preferences button (
File Tools.

) in the

The Global Info dialog will appear.


2. Select General::Page on the left side of the dialog box.
The Page panel will appear in the right side of the dialog box.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

22

3. Enter the information in the right portion of the dialog box.


Measurement

Choose the measurement unit style you desire here.

4. Click OK.
Switching to a different panel will automatically save your choices.

To edit tags
DigitalMicrograph keeps an internal database of assorted information such as user
preferences, algorithm options, and other data vital to the operation of
DigitalMicrograph. You can directly edit this information.
Editing tags is an advanced use of DigitalMicrograph and should, in general, not be
performed unless you have explicit instructions on how to do so. It is possible to make
DigitalMicrograph unlaunchable by editing tags.
1. Choose Global Info from the File menu or click the Preferences button (
File Tools.

) in the

The Global Info dialog will appear.


2. Select General::Tags on the left side of the dialog box.
The Tags panel will appear in the right side of the dialog box.
3. Enter the information in the right portion of the dialog box.
A list of tags is displayed. You can use the twist-down controls to open up
groups and lists of tags.
Edit
Add
Remove

Click this button to edit the selected tag


Click this button to add a new tag
Click here to remove the selected tag

4. Click OK.
Switching to a different panel will automatically save your choices.

1.2.10 Session Information

Session Information
When you acquire an image with a Camera or the DigiScan, DigitalMicrograph automatically
adds meta-data to the image. This meta-data can later be viewed to give information about
the image.

Copyright 2012 Gatan Inc. All Rights Reserved.

23

DigitalMicrograph

The meta-data is separated in 2 groups: microscope data and session data. They can be
viewed in the Global Info dialog under Session:Microscope Info and Session:Session Info.

Global Microscope Info


The Microscope Info page looks like this:

(This dialog can look slightly different depending on the capabilities of the actual
microscope you are connected to.)
Here you can view and change information about the state of the microscope; some
fields are filled in automatically by DigitalMicrograph if the software can
communication with a microscope.

Global Session Info


The Session Info page looks like this:

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

24

With a clean install of DigitalMicrograph there will just be the three entries in the
General area, and the Custom area will be blank. To change the entries in the custom
area hit the

button. This will show the following dialog:

Copyright 2012 Gatan Inc. All Rights Reserved.

25

DigitalMicrograph

This dialog shows all the fields currently defined for the Session Info.

To add a Session Field


Enter Name of field, and choose data type from the drop list
Hit Add button

To Remove a Session Field


Select a field from the list box
Hit the Remove button. Note you can not remove the fields listed in the General
section, i.e. the first 3 items.

To change a Session Field


Select a field from the list box
Change the name and/or data type
Hit Update button

Image Info

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

26

When acquiring an image, the previously defined microscope and session info will be
copied to the image, and it can be viewed using the Image Display Info dialog.
Opening the Image Display Info dialog will include the following 2 pages:

Copyright 2012 Gatan Inc. All Rights Reserved.

27

DigitalMicrograph

Note that all the information from the Global Info is copied over into the image. Also
note that the Session page for Image Display Info does not have a
button. Here
you can only view and edit the Session data, but you can not change what fields are
displayed in the Session page.

1.2.11 Importing Images

Importing Images
DigitalMicrograph can import some images stored in text or binary files with unrecognized file
formats. You will need to know certain information about the image stored in the file in order
to use this technique.

To import images
You need to know the data type and the width, height and depth of the image to import
a binary image. To import a text image, the pixels in the image need to be separated
by tabs. DigitalMicrograph can determine the width and height of text images if each
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

28

row is separated by a carriage return or line feed.


1. Choose Import Data under the File menu.
You will be asked to select a file to open.
2. Find and open the desired data file.
The Import Image dialog box will appear.
3. Select the data type from the Data Type pop-up menu.
If you are importing a file that contains binary data, continue with Step 4.
If you are importing a file that contains text data, skip to Step 9.
4. Click on the Binary button.
This will enable the options for Binary data and dim the options for Text data.
5. In the Offset edit box, enter the offset at which to start reading the data within the
file.
The offset is specified in bytes.
6. To enable byte swapping, click on Swap Data Bytes.
On the Macintosh, the high-order bytes are stored first. However on the PC
and some other systems, the low-order bytes are stored first and byte
swapping is necessary.
7. Enter the size of the image in the Width and Height edit boxes.
8. Click OK to import the image.
If there are no problems, a new image will be created. See "About import
problems" for a discussion of possible problems.

The following steps describe importing from a text file:


9. Click on the Text button.
This will enable the options for Text data and dim the options for Binary data.
10. Enable or disable Lines Are Rows as appropriate.
If each row of data ends with a line feed,i.e., lines are rows, then
DigitalMicrograph can determine the width of the image. Enabling this item

Copyright 2012 Gatan Inc. All Rights Reserved.

29

DigitalMicrograph

enables Get Size By Counting.


If you disable Lines Are Rows, skip to Step 12.
11. Enable or disable Get Size By Counting as desired.
If you enabled Lines Are Rows, DigitalMicrograph can determine the width and
height of the image. Enabling this item disables the Width and Height edit
boxes.
If you enable Get Size By Counting, skip to Step 13.
12. In the Width and Height edit boxes enter the size of the image.
13. Click OK to import the image.
If there are no problems, a new image will be created. See "About import
problems" for a discussion of possible problems.

About import problems


If DigitalMicrograph cannot import the file according to the parameters that you
specify, it will display a dialog describing the error.
For binary files, the file length as shown in the Import Image dialog box should be
greater than or equal to the (width * height * depth * size of the data type) + offset.
Additionally, if you enter an erroneous width or offset, DigitalMicrograph may be able to
construct an image, but it will appear distorted. An erroneous length can also result in
garbage appearing at the end of the image.

1.2.12 Databar

Databar
DigitalMicrograph contains a feature called the databar. This corresponds to displaying extra
information with the image, either in image mode or page mode. (For more info on image and
page mode see "About Targets").

Setting up the databar


To define what the Databar should look like, open the Global Info dialog and select
Data Bar::Page Mode, or Data Bar::Image Mode.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

30

Check any items that you want to add to the image.

Custom items
Custom items can be defined using the Session Info page.
To view these items, hit the Custom Data... button. You will see the following dialog
(the contents depends on what you set-up under the Session Info):

Select the fields you want to display and hit OK.

Copyright 2012 Gatan Inc. All Rights Reserved.

31

DigitalMicrograph

Displaying the databar


To display the Databar use the

button or the

button on the File tools toolbar.

When hitting the


button, the databar is added without changing the view mode of
the image. I.e. if the image is displayed in image mode, the databar for image mode is
added, if the image is displayed in page mode, the databar for page mode is added.
When hitting the
button the image is first changed to page mode, and then the
page mode databar is added. This button is also revered to as "Print Preview".
To remove the databar hit the

button.

After creating the databar, you can change the location of each of the items. The new
locations can be made the new default setting by choosing the menu item Edit::Data
Bar:: Use as global default.

1.3

Image Display
Image Display
DigitalMicrograph provides several methods of displaying the data in an image. Some of the
methods are appropriate for only certain types of image data, while others work with any type
of image data.
The method that DigitalMicrograph uses to display an image is called the image display type.
DigitalMicrograph provides several image display types.
Raster image display.
Surface Plot image display.
RGB image display.
Line Plot image display.
Spreadsheet image display.
Each of these image display types has many options associated with it. Furthermore, some
of the image display types (such as RGB) are only appropriate for certain types of data (RGB
data only).

To change image display type


You can change how an image is displayed.
1. If you are viewing the image document in page mode, select the image of which
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

32

you want to change the display type.


2. Choose a new image display type in the Display Type submenu under the Display
menu.
The check mark indicates the display type of the selected image.
Only the image display types that are valid for the selected image will be
enabled.
Upon selection of a new display type, DigitalMicrograph will change the image
display type of the image to the newly selected one. Any specific information
you configured for the old image display will be lost.

To create a new image from the display


Sometimes it will be convenient to generate a new image representing everything that is
displayed in the image window. If you have multiple images, objects, and annotations on the
page, you can consolidate all of these into a single new image. However, the individual
components on the page will not be editable in the new image display, which will be rendered
at screen resolution (roughly 72 pixels/in.).
1. Select the image document of which you want to create a display.
2. Make the display look how you want it to look in the new image.
You can place the image document in page or image mode to view either all of
the images or only a single image.
3. Choose Create Image from Display under the Display menu.
A new image document will appear that contains a single image representing
the original image document (as it appeared on the screen and at screen
resolution).

1.3.1

About Image Displays

About Image Displays


In order to display an image using Raster or Surface Plot display types, DigitalMicrograph
must first map the image's data to the values 0 through 255. To display in gray-scale, the
values 0 to 255 are then associated with different gray-scale values, e.g. 0 corresponds to
black and 255 corresponds to white. To display in color, each value from 0 to 255 is
associated with a color. In the rest of this section, gray-scale values are considered to be just
a specific case of a color transformation. The section below describes these
transformations.

About Transformations
DigitalMicrograph maps an image's original data values to a color or gray-scale value
Copyright 2012 Gatan Inc. All Rights Reserved.

33

DigitalMicrograph

through a sequence of steps.


1. Determine the contrast limits of the image's data (see "About Contrast Limits").
DigitalMicrograph uses two parameters, the low- and high-contrast limits, to
map the image's original data into a range suitable for display of the image.
Pixels in the original image below the low-contrast limit are treated as if they
were at the low-contrast limit and those above the high-contrast limit are
treated as it they were at the high-contrast limit.
DigitalMicrograph can determine these contrast limits "automatically" by
surveying the image, or "manually" using values entered by the user.
When DigitalMicrograph surveys the image, it uses one of the survey methods
(see "To change the survey method") to estimate or calculate exactly the
minimum and maximum values in the image. These values are used as the
low- and high-contrast limits. When using the manual method (see "To enter
contrast limits manually"), the user must enter these values.
DigitalMicrograph can also ensure a minimum difference between the low- and
high-contrast limits. See "To set the minimum contrast limit value". A
minimum contrast level prevents un-aesthetic display of images with very low
contrast.

2. Transform each mapped data value into a color index (see "About Contrast
Transformations").
The mapped image values are then transformed into a color index that
indicates which color in the color table to use for displaying a particular pixel.
The Contrast Transform lines in the Histogram depict how this transformation
is performed. DigitalMicrograph supplies a number of standard contrast
transform methods (see "To change the contrast transformation method") and
allows you to build a custom one if you desire (see "To edit the custom
Contrast Transformation line" ).
3. Display the pixel using the color table of the image (see "About Lookup Tables").
DigitalMicrograph uses the color index to correlate each color in the color table
with pixels with specific intensities in the image. DigitalMicrograph supplies a
number of standard color tables, such as the gray-scale table, for use in
images and allows you to build a custom one if you desire (see "To change
the color table" and "To adjust colors via Histogram palette" ).

About Histograms
DigitalMicrograph will automatically calculate the histogram of an image displayed
using Raster or Surface Plot display types, and display it in the Histogram palette. The
Histogram palette also displays the Contrast Transform lines and the color table in the
Color Bar on the left of the palette.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

34

The horizontal axis of the histogram represents data values with the left-most side
corresponding to the low contrast limit and the right-most side corresponding to the
high contrast limit. The vertical axis of the histogram represents the number of pixels
with a particular data value.
The histogram can be used to change the low- and high-contrast limits, to edit a
custom Contrast Transformation, and to change the color table.
1.3.1.1

About Contrast Limits

About Contrast Limits


When DigitalMicrograph tries to automatically determine the contrast limits to use in
displaying an image, it surveys the image to determine the minimum and maximum values in
the image. DigitalMicrograph employs several survey methods from which you can choose.

Cross-wire
Checks the values only on a cross going through the center of the image. This
method is quite fast and immune to extreme values except under the cross. It will not
optimize the contrast if the desired features do not fall under the cross.

Sparse
Checks the values only on a distributed set of positions throughout the image. This
method is quite fast and immune to extreme values except under the distribution. It is
quite good at optimizing the contrast of the entire image.

Whole image

Copyright 2012 Gatan Inc. All Rights Reserved.

35

DigitalMicrograph

Checks the values at every single pixel. This method is much slower and not immune
to extreme values within the image. It is quite good at optimizing the contrast of the
entire image.

Reduction
Checks the values by dividing the image into 16 equal squares. This method is much
slower and not immune to extreme values within the image. It is quite good at
optimizing the contrast of the entire image.

None
Does not check the values. Relies on the user entering proper contrast limit values in
the Object InfoDisplay-Contrast dialog.

To change the survey method


1. If you are viewing the image document in page mode, select the image for which
you want to change the survey method.
2. Choose Image Display under the Display menu, or hit Ctrl-D, or right click on the
display and select ImageDisplay... from the menu.
The Image Display Info dialog will appear.
3. Select Display::Contrast on the left side of the dialog box.
The Contrast panel will appear in the right side of the dialog box, as shown in
the figure.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

36

4. Select the desired survey method from the Survey pop-up menu.
When choosing the sparse method you can specify how many samples
should be used in the total image for the survey.
5. Click OK

To enter contrast limits manually


If you turn Survey off or don't want DigitalMicrograph to automatically determine
contrast limits, you can enter them manually.
1. If you are viewing the image document in page mode, select the image for which
you want to enter contrast limits manually.
2. Choose Image Display under the Display menu, or hit Ctrl-D, or right click on the
display and select ImageDisplay... from the menu.
The Image Display Info dialog will appear.
3. Select Display->Contrast on the left side of the dialog box.
The Contrast panel will appear in the right side of the dialog box.
4. Select None from the Survey pop-up menu.
5. Enter the desired contrast limits in the Low and High fields.
Copyright 2012 Gatan Inc. All Rights Reserved.

37

DigitalMicrograph

6. Click OK.

To set the minimum contrast limit value


In order to improve the display of unaesthetic low-contrast images, you can set a
minimum contrast level that is used after automatically determining the contrast limits
through one of the methods above.
1. If you are viewing the image document in page mode, select the image for which
you want to set a minimum contrast limit value.
2. Choose Image Display under the Display menu, or hit Ctrl-D, or right click on the
display and select ImageDisplay... from the menu.
The Image Display Info dialog will appear.
3. Select Display->Contrast on the left side of the dialog.
The Contrast panel will appear in the right side of the dialog box.
4. Enter the desired minimum contrast limit value in the Min. Contrast Range field.
5. Click OK.

To change contrast limits with the Histogram palette


The histogram palette can be used to change the contrast limits used in the image
display.
1. If you are viewing the image document in page mode, select the image for which
you want to set a minimum contrast limit value.
2. Using the Pointer tool, drag over the Histogram to select the desired input range.
The selected area will be drawn in yellow.
When releasing the mouse, the image and histogram will be redrawn with the
new contrast limits.
You can set the contrast limits back to automatically determined values by
clicking on the bottom color bar of the Histogram palette.

To ignore Outliers
Images can contain extreme outliers that can affect the contrast limits if the pixels
containing the outlier values are used for the survey. To prevent this from happening
you can choose to ignore a certain percentage of outliers.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

38

1. If you are viewing the image document in page mode, select the image for which
you want to set a minimum contrast limit value.
2. Choose Image Display under the Display menu, or hit Ctrl-D, or right click on the
display and select ImageDisplay... from the menu.
The Image Display Info dialog will appear.
3. Select Display->Contrast on the left side of the dialog.
The Contrast panel will appear in the right side of the dialog box.
4. Enter the desired percentage for low and high outliers to be ignored.
A very small percentage, such as 0.2 generally does the trick, unless you have
an extreme number of bad pixels.
5. Click OK.

To set up hysteresis
When acquiring images from hardware, noise in the images can cause different
contrast limits being calculated for each frame. This will cause some annoying flicker
in the overall image. To reduce this effect you can set a level of hysteresis, which
means that the contrast limits of an image will not be updated unless the survey finds
values outside a specified range.
1. If you are viewing the image document in page mode, select the image for which
you want to set a minimum contrast limit value.
2. Choose Image Display under the Display menu, or hit Ctrl-D, or right click on the
display and select ImageDisplay... from the menu.
The Image Display Info dialog will appear.
3. Select Display->Contrast on the left side of the dialog.
The Contrast panel will appear in the right side of the dialog box.
4. Enter the desired percentage for Min and Max after: "Update if min or max change
by".
5. Click OK.

To save the default contrast settings


You can change the default contrast settings that DigitalMicrograph uses when it
creates a new image.

Copyright 2012 Gatan Inc. All Rights Reserved.

39

DigitalMicrograph

1. If you are viewing the image document in page mode, select the image for which
you want to change the survey method.
2. Choose Image Display under the Display menu, or hit Ctrl-D, or right click on the
display and select ImageDisplay... from the menu.
The Image Display Info dialog will appear.
3. Select Display->Contrast on the left side of the dialog box.
The Contrast panel will appear in the right side of the dialog box.
4. Select your desired contrast settings.
5. Click on the Save Defaults button.
6. Click OK.
1.3.1.2

About Contrast Transformations

About Contrast Transformations


DigitalMicrograph provides a number of standard contrast transformation methods.

Linear
The Linear method maps data linearly from the contrast limits to the color index. It can
also apply a gamma transformation. Brightness, Contrast, and Gamma control the
offset, slope, and shape of the line used in the mapping. See "To change Brightness/
Contrast/Gamma graphically".

Equalized
The Equalized method maps data so as to optimize color usage based on the
histogram. Each color will have approximately the same number of pixels mapped to
it, so more colors will be used in intensity ranges with more pixels.

Pseudo-Contour
The Pseudo-Contour method maps data repeatedly in a linear fashion from the
contrast limits to the color index. The contrast and contours control the slope of each
contour line and the number of contours used in mapping. See "To change Contrast/
Contours".

Custom
The Custom method maps data according to a custom mapping. You change the
mapping in the Histogram palette. See "To edit the custom Contrast Transformation
line".

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

40

To change the contrast transformation method


1. If you are viewing the image document in page mode, select the image for which you
want to set the contrast transformation method.
2. Choose Image Display under the Display menu, or hit Ctrl-D, or right click on the
display and select ImageDisplay... from the menu.
The Image Display Info dialog will appear.
3. Select Display->Contrast on the left side of the dialog box.
The Contrast panel will appear in the right side of the dialog box.
4. Select the desired method in the Mode pop-up menu.
5. Click OK.

To edit the custom Contrast Transformation line


You can build a custom Contrast Transformation line using the Histogram palette.
1. If you are viewing the image document in page mode, select the image for which you
want to set a custom Contrast Transformation line.
2. Choose Image Display under the Display menu, or hit Ctrl-D, or right click on the
display and select ImageDisplay... from the menu.
The Image Display Info dialog will appear.
3. Select Display->Contrast on the left side of the dialog box.
The Contrast panel will appear in the right side of the dialog box.
4. Select Custom in the Mode pop-up menu.
5. Click OK.
6. Draw the desired Contrast Transformation line in the Histogram palette.
The cursor will switch to a pencil when you move it over the Histogram
palette.

To change Brightness/Contrast/Gamma graphically


You can change the brightness, contrast, and gamma of an image graphically.
Brightness, contrast and gamma are only available when the image display is using
the linear contrast mode.
1. If you are viewing the image document in page mode, select the image for which you
want to adjust the brightness, contrast, and gamma.
Copyright 2012 Gatan Inc. All Rights Reserved.

41

DigitalMicrograph

2. Adjust the brightness, contrast, and gamma values in the Display Control palette.

To reset the values to 0.50 click the text below the slider.

To change/save default Brightness/Contrast/Gamma


settings
You can change/save the default settings that DigitalMicrograph uses when it
creates a new image.
1. If you are viewing the image document in page mode, select the image for which you
want to change the settings.
2. Choose Image Display under the Display menu, or hit Ctrl-D, or right click on the
display and select ImageDisplay... from the menu.
The Image Display Info dialog will appear.
3. Select Display->Display on the left side of the dialog box.
The Display panel will appear in the right side of the dialog box.
4. Select your desired settings.
5. Click on the Save Defaults button.
6. Click OK.

To change Contrast/Contours
You can change the contrast and number of contours of an image using a Pseudo
Contrast contrast mode.
1. If you are viewing the image document in page mode, select the image for which you
want to adjust the number of contours and the contrast of the contours.
2. Choose Image Display under the Display menu, or hit Ctrl-D, or right click on the
display and select ImageDisplay... from the menu.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

42

The Image Display Info dialog will appear.


3. Select Display->Contrast on the left side of the dialog.
The Contrast panel will appear in the right side of the dialog box.
4. Select the Pseudo-Contour in the Mode pop-up menu.
5. Click OK.
6. Adjust the contrast and number of contours in the Display Control palette.
1.3.1.3

About Lookup Tables

About Lookup Tables


DigitalMicrograph provides a number of standard color tables:
Greyscale
The greyscale table is the default table used when creating new images.
Rainbow
The rainbow table provides a sequence of colors ranging from red to purple,
corresponding to the order of colors in the rainbow.
Temperature
The temperature table provides a sequence of colors supposedly
corresponding to the perceived colors of a glowing object. Colors range from
black, through blue, green, red and yellow to white.
It is also possible to create custom color tables and save them for later use.

To change the color table


You can change the color table that DigitalMicrograph uses to display an image.
1. If you are viewing the image document in page mode, select the image for which you
want to change the color table.
2. Choose Image Display under the Display menu, or hit Ctrl-D, or right click on the
display and select ImageDisplay... from the menu.
The Image Display Info dialog will appear.
3. Select Display->Color on the left side of the dialog box.
The Color panel will appear in the right side of the dialog box.
4. Select a desired color table from the Table pop-up menu.

Copyright 2012 Gatan Inc. All Rights Reserved.

43

DigitalMicrograph

5. Edit a color in the color table manually by double clicking on the color.
A dialog box asking you to select the new color will appear.
6. Edit a range of colors manually by dragging over the range of colors.
Two dialog boxes asking you for the color at the start of the range and the
color at the end of the range will appear.
7. Save the color table by clicking on the Save button.
A dialog asking for a filename to save it under will appear.
You do not need to save the color table, but if you don't save it, it will only be
available on this particular image.
8. Click OK.

To adjust colors via Histogram palette


You can change an image's color table directly in the Histogram palette.
1. If you are viewing the image document in page mode, select the image for which you
want to change the color table.
2. Drag within the color bar along the left side of the Histogram palette.
Drag through a desired range and DigitalMicrograph will distribute colors
evenly between the color where you started dragging and the color where you
stopped dragging. The color where you started dragging will remain the same
and the color where you stopped dragging will become the color you select
for the endpoint.

1.3.2

Using Raster Image Displays

Using Raster Image Displays


The Raster image display is displayed two-dimensionally like a conventional black-and-white
photograph. Images acquired from cameras will typically be displayed in Raster image
displays. Each pixel in the image is displayed as a greyscale value or an RGB color
determined by indexing the intensity into a color table (see "About Image Displays").

To add/remove captions
DigitalMicrograph can display captions indicating the calibration of the image.
Captions are off by default.
1. If you are viewing the image document in page mode, select the image to which
you want to add or from which you want to remove captions.
2. Choose Image Display under the Display menu, or hit Ctrl-D, or right click on the
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

44

display and select ImageDisplay... from the menu.


The Image Display Info dialog will appear.
3. Select Captions::Captions on the left side of the dialog box.
The Captions panel will appear in the right side of the dialog box.
4. Click on the Caption check box to enable or disable captions.
5. Click on the Save Defaults button to indicate that you always want captions turned
on or off for all new images.
6. Click OK.

To see a value at a particular image position


DigitalMicrograph will display the position of the cursor within the image and the
intensity of the pixel at that position in the Image Status palette. The values will be
displayed in calibrated units if the image is calibrated.
Move the cursor over the Raster image display to see the pixel position and value in
the Image Status palette.

1.3.3

Using Surface Plot Image Displays

Using Surface Plot Image Displays


The Surface Plot image displays your data as a three-dimensional surface.
You can change the viewpoint from which you observe the surface plot and you can choose
whether the surface plot is shaded or not. The intensity of each pixel in the image is displayed
as a greyscale value or an RGB color determined by indexing the intensity into a color table
(see "About Image Displays").

To change the view of a surface plot


You can change the view of the surface plot.
Change the view of the surface plot by dragging one of the three adjustment
handles.
Your view of the data will always be from the same side.

To turn Shading on or off


You can disable or enable Shading on the surface plot. The surface plot will be
rendered slightly faster if Shading is disabled.
1. If you are viewing the image document in page mode, select the image for which
Copyright 2012 Gatan Inc. All Rights Reserved.

45

DigitalMicrograph

you want to adjust Shading.


2. Choose Image Display under the Display menu, or hit Ctrl-D, or right click on the
display and select ImageDisplay... from the menu.
The Image Display Info dialog will appear.
3. Select Surface Plot->Shading on the left side of the dialog box.
The Shading panel will appear in the right side of the dialog box.
4. Click on the Shading check box to enable or disable shading.
5. Click OK.

1.3.4

Using RGB Image Displays

Using RGB Image Displays


The RGB display is displayed two-dimensionally, like a conventional color photograph. The
intensity of each pixel in the image is directly determined by the value of the image (which can
only be RGB data type). The RGB image display looks similar to the raster image display.

To see a value at a particular image position


DigitalMicrograph will display the position of the cursor within the image and the
intensity of the pixel at that position in the Image Status palette. The values will be
displayed in calibrated units if the image is calibrated.
Move the cursor over the RGB image display to see the pixel position and value.

1.3.5

Using Line Plot Image Displays

Using Line Plot Image Displays


The Line Plot display is displayed as a one-dimensional plot. Images acquired from onedimensional devices such as spectrometers will typically be displayed with Line Plot image
displays. If a two-dimensional image is displayed using a line plot, each row in the image will
be superimposed on the line plot in a different color (up to eight different colors).

To see a value at a particular image position


DigitalMicrograph will display the position of the cursor within the line plot and the
intensity of the pixel at that position in the Image Status palette. The values will be
displayed in calibrated units if the image is calibrated.
Move the cursor over the line plot image display to see the pixel position and value.

To adjust line plot data view


Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

46

You can control many aspects of how the image is displayed from the Line Plot panel
in the Image Display Info dialog.
1. If you are viewing the image document in page mode, select the image for which
you want to adjust the line plot data view.
2. Choose Display Type::Line Plot under the Display menu.
3. Choose Image Info... under the Display menu, or hit Ctrl-D, or right click on the
display and select Image Info... from the menu.
The Image Display Info dialog will appear.
4. Select Display::Line Plot on the left side of the dialog box.
The Line Plot panel will appear in the right side of the dialog box.

Change the desired low and high limits of image data to display in the Line Plot.
Editing these values automatically turns off automatic survey.
You do not need to enter values here if you want DigitalMicrograph to calculate
the value automatically.

Copyright 2012 Gatan Inc. All Rights Reserved.

47

DigitalMicrograph

Change the Scale


The y-axis of a line plot can be displayed in linear mode and in logarithmic
mode. This is especially useful for EELS spectra which can have an
enormous dynamic range. An EELS spectrum containing the zero-loss peak
is dominated by this peak in linear mode. In logarithmic mode both the peak
and the much lower Plasmon and edge signals are visible at the same time.

All of the tools for changing the display range of the line plot work in log mode
just as they did in linear mode. You can change the display mode in 2 ways:
right click on the line plot display and choose "Linear Scale" or "Log
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

48

Scale", or
open the Image Info dialog, select the "Display:Line Plot" page, and
choose linear or log from the Scale group box.
Technical note:
It is impossible to take the logarithm of values 0 and smaller, and the logarithm
of values between 0 and 1 are negative. Therefore we want to avoid data
values less than 1. To accomplish this we first take the modulus of the data,
and then add 1 to all data before taking the logarithm. After applying the
logarithm, the sign of the original data is restored. The main result of this is
that if you have original data with values close to zero, then the linear plot and
the logarithmic plot will look very similar. For data much larger than 1 the
difference between this approach and the simple log of the data is negligible.
This is almost always the case for EELS data and makes this tool very useful.
Change the Auto Survey option
Auto Survey for the Low and High values can be set independently by checking
the appropriate check boxes.
Reset Auto Survey
When manually changing the survey, for example by dragging the axis,
DigitalMicrograph automatically turns off Auto Survey. To quickly turn Auto
Survey back on, you can double click the vertical axis.
Auto Survey Displayed Region
When checking "Displayed Region" then DigitalMicrograph will only use the
actual data displayed to calculate the display limits. So if you have an EELS
spectrum with a zero loss peak, and you zoom in on an area not containing
that peak, then DigitalMicrograph will automatically scale to optimize the view
of the displayed data. Here is the same spectrum as above, but with the zeroloss peak moved off the display:

Copyright 2012 Gatan Inc. All Rights Reserved.

49

DigitalMicrograph

Auto Survey Fix baseline


When choosing the "Fix baseline" check box, then the baseline will always be
zero, i.e. the vertical axis will go from zero up, or if all data is negative, from
zero down. This is particularly useful for data that actually has a baseline equal
to zero, e.g. EELS data.
4. Click OK to close the dialog.

To adjust line plot display options


You can control a number of options affecting the line plot display. These options are
captions, background, grid, frame and legend. The Captions option includes the tick
marks and the labels at the tick marks. Background is the background color within
the graph area. This is normally set to a very light grey. With background off it
becomes white. Grid refers to the grid lines within the graph area. Frame refers to the
boxes that are drawn around the graph area and around the legends. Finally, legend
refers to buttons that get drawn to the right of the graph area. For more information
about what to do with legends, see "Using Line Plot Legends".
1. If you are viewing the image document in page mode, select the image for which
you want to set options.
2. Choose Image Display under the Display menu, or hit Ctrl-D, or right click on the
display and select ImageDisplay... from the menu.
The Image Display Info dialog will appear.
3. Select Display::Options on the left side of the dialog box.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

50

The Options panel will appear in the right side of the dialog box.
4. Check or uncheck the desired options.
5. Click OK.
Instead of using the Image Display Info dialog, you can also toggle display of the
legends by right clicking on the line plot, and then selecting Hide Legend or Show
Legend from the pop-up menu.

To set the default window size for a line plot


You can set the default window size for a line plot. All line plots created and displayed
in windows will use the default window size.
1. Create a line plot and size the window to the desired size.
2. Choose Image Display under the Display menu, or hit Ctrl-D, or right click on the
display and select ImageDisplay... from the menu.
The Image Display Info dialog will appear.
3. Select Display::Placement on the left side of the dialog box.
The Placement panel will appear in the right side of the dialog box.
4. Click on the Save Defaults button.
5. Click OK.

To move the line plot display within the frame


You can move the line plot display within the frame using either a tool or by using the
keyboard.
Click on the line plot axes with the Pointer tool and drag.
This will graphically move the Line Plot within its frame. You can only move
horizontally or vertically depending on which axis you clicked on.
Click on the line plot axes with the Move tool from the Line Plot Tools and drag.
This will allow you to graphically move the Line Plot within its frame both
horizontally and vertically.
Use the following keyboard commands to move the Line Plot within its frame.
Press the 8 (up), 6 (right), 2 (down), and 4 (left) keys on the numeric keypad.
Copyright 2012 Gatan Inc. All Rights Reserved.

51

DigitalMicrograph

Press the 5 key to reset to the center.


The Line Plot Tools toolbar

To scale the line plot display within the frame


You can scale the line plot display within the frame using different methods.
Click on the Line Plot with the Horizontal or Vertical Zoom tools from the Line
Plot Tools and drag.
Click on the Line Plot with the Area Zoom tool from the Line Plot Tools and
drag.
Click on the line plot axes with the Pointer tool and drag while holding the
Control key down.
It is also possible to accomplish the same task using Regions of Interest.
1. Create an ROI on the line plot.
For information on how to add ROI's to a line plot see "Using Regions of
Interest".
2. Right click on the line plot and choose Zoom to ROI or Zoom Vertically to ROI from
the pop-up menu.
When choosing Zoom Vertically to ROI only the vertical axis is changed to
optimize display of the data within the ROI. When choosing Zoom to ROI, both
vertical and horizontal axes are changed.
If more than one ROI is present the display is zoomed to the selected ROI. If
none of the ROI's are selected nothing happens. (You select an ROI by
clicking on its badge, which is displayed as a + when not selected and as a
solid square when selected.)
Note that after you choose Zoom to ROI, the ROI that was zoomed to is
deleted from the line plot.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

52

To reset the line plot display


You can reset the line plot display to its original horizontal and vertical zoom settings.
Click on the Line Plot with the Area Zoom tool and do not drag.
Right click on the Line Plot and choose Home Display from the pop-up menu.
Hit the 5 key on the numeric keypad.

1.3.6

Using Line Plot Legends

Using Line Plot Legends


When Line Plot legends are made visible (see "To adjust line plot display options" on how to
make legends visible), a whole range of more advanced operations on Line Plots become
available. The legend is displayed with the text "SliceX" with a box drawn around it in a color
matching the corresponding curve.

To adjust the colors of a line plot


The colors of the curves in a line plot can be changed.
1. Right click on the legend and choose Draw Style from the pop-up menu.
2. Choose Draw Fill, Draw Line, Line Color... or Fill Color... from the sub
menu.
Draw Fill and Draw Line are toggle settings. A curve can be shown with a line,
or with fill or both. The Color... items pop up a dialog for choosing a color.

To copy/paste or drag/drop line plot data


Line Plots can display more than one line at a time. One way to accomplish this is by
creating an image of, for example, size 512 by 8. Display it in Line Plot mode, and 8
curves will be shown. Another way is to copy and paste, or drag and drop data from
one line plot into another.
To copy/paste data from one line plot to an other:
1. Right click on the legend of a slice you want to copy, and select Copy from
the pop-up menu.
2. Select the destination image, right click on the display and select Paste
from the pop-up menu.
You can also select the destination image and hit Ctrl-V on the keyboard to
paste the image

Copyright 2012 Gatan Inc. All Rights Reserved.

53

DigitalMicrograph

To drag and drop data from one line plot to an other:


Right click on the source line plot, and drag to the destination line plot
All the slices in the source plot will be copied to the destination plot.

To hide/show slices
Slices can be shown and hidden. The colored outline around the word "SliceX"
indicates that the slice is shown.
To show just one slice:
Double click on the legend and all other slices will be hidden, or
Right click on the legend, and choose Hide Others from the pop-up menu.
To hide a particular slice:
Right click on the legend, and choose Hide SliceX from the pop-up menu.
To show all slices:
Right click on the legend, and choose Show All from the pop-up menu.

To order slices
The order in which the legends are drawn indicates the order in which the slices are
drawn. Slices that are higher up in the order will be drawn behind slices that are
farther down.
You can change the order of the slices:
1. Right click on the legend of the slice you want to move in the order.
2. Select Send Behind or Bring to Front on the pop-up menu.
Note that if you have a slice in the foreground with its fill drawn, it can obscure
many slices behind it. This is why the default configuration has the background
slice drawn as Fill, and all other slices drawn as Lines.

To align slices
Slices can be aligned with respect to one another in different ways. If slices are
calibrated, the different slices will originally be aligned with respect to their calibration.
This means that the labels on the axes apply to all different slices. For any but the
back most slice, the alignment can be changed in the horizontal direction, vertical
direction or both.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

54

Choices for alignment in the horizontal direction are "Calibrated" and "Uncalibrated".
"Uncalibrated" means that the alignment is done based on pixels.
Choices for vertical alignment are "Calibrated", "Uncalibrated", "Integral", "Maximum"
and "Baseline". "Calibrated" and "Uncalibrated" alignment is similar to that for
horizontal alignment, except that here the intensity calibration of the data is used.
"Integral" alignment makes the area on both curves the same. "Maximum" alignment
sets the maxima the same, and "Baseline" alignment aligns the zero's of the
uncalibrated data, leaving the scale unchanged.
Vertical alignments can also be performed on a sub-set of the data by first creating a
selection on the Line Plot.

To attach/detach slices
When aligning slices as described above, you can only change the relative size and
position of the different slices in certain predefined ways. This is because the slices
are "attached". To give the user more freedom in positioning slices with respect to
one another, slices can be detached.
To detach a slice:
1. Right click on the legend of the slice you want to detach.
2. Select Horizontal Constraints from the pop-up menu.
3. From the sub-menu select "Detach", "Baseline Fixed" or "Scale Fixed".
When choosing "Detach" the slice is fully detached in the horizontal directly
and both the offset and scale can be changed. When choosing "Baseline
Fixed" only the scale can be changed and when choosing "Scale Fixed" only
the offset can be changed.
After fully or partially detaching a slice, the horizontal offset and/or scale of the slice
can be changed:
1. Click on the line plot.
A vertical line will be drawn.
2. Click near the vertical line and drag the mouse.
The whole slice will move wit the cursor.
3. Click near the vertical line, hold down the Control key, and drag the mouse.
The scale of the slice will change.
The slice can also be detached and moved vertically in the same way.

Copyright 2012 Gatan Inc. All Rights Reserved.

55

DigitalMicrograph

Recalibrate
After a slice has been detached and moved around it can acquire a new calibration.
Right click on the legend, and choose Recalibrate Slice from the pop-up menu.

1.3.7

Using Speadsheet Image Displays

Using Spreadsheet Image Displays


Spreadsheet display is displayed as a table of numbers representing pixels in the image. It
can show any type of image data.

To edit a pixel in an image


You can edit a pixel within a spreadsheet.
Double click on the cell containing the pixel you want to edit.
The Edit Value dialog will appear for you to enter a new value.

1.3.8

Using Image Displays with Complex Data

Using Image Displays with Complex Data


Images that have a complex data type need to be converted to a real number (as opposed to
a complex number) in order to be displayed.

To change the display of complex data


DigitalMicrograph supplies five methods of converting complex data to real data for
display.
1. If you are viewing the image document in page mode, select the image for which
you want to set the complex data conversion method.
2. Choose Image Display under the Display menu.
The Image Display Info dialog will appear.
3. Select Display->Complex on the left side of the dialog box.
The Complex panel will not appear if the image does not have a complex data
type.
4. Select the desired conversion method in the Complex Display pop-up menu.
5. Enter the Range parameter used in calculating the log of the modulus, if necessary.
6. Click OK.
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

1.4

56

Image Documents
Image Documents
DigitalMicrograph stores images in image documents that contain a representation of a
printed page upon which you can lay out images, objects, and other annotations.
Image documents are displayed in image windows and contain a graphical representation of
a page upon which images, objects, and annotations can be placed.

About pages
When you want to print your page to a laser, dye-sublimation, or other type of printer,
you will need to lay out your images, objects, and annotations upon the page.
DigitalMicrograph can represent this page graphically within an image window. The
image document may also contain images, objects, and annotations that lay outside
the boundaries of the page. DigitalMicrograph keeps track of objects both on and off
the page.
The page is represented by the white area in the image window. The rectangular
dotted outline indicates the printable area of the page. Any objects or portions of
objects outside this rectangle will not be printed.

About objects
Objects in DigitalMicrograph are any item within an image document that can be
manipulated directly. Objects include images, boxes, arrows, lines, ovals, masks,
particles, scale markers, etc.
Objects are attached to a parent. The default parent is called a target. The parent can
either be the page itself or an image on the page. Objects will move and scale with
their parent. For example, an object attached to an image will move when the image is
moved and become larger or smaller when the image is made larger or smaller.

About modes
An image document has two modes by which you can view it. In page mode, a
representation of the page is displayed and you can lay out multiple images on the
page. In image mode, a single image is displayed. Its position on the page is set by
switching to page mode, adjusting its position, and then switching back to image
mode.

About targets
In page mode, when you add a simple object such as a text annotation, a line, or a
box to an image document, it is attached to a target. The target can either be the page
or an image contained in the image document. Objects attached to the page will move
and scale when the page is moved or scaled. Objects attached to an image will move

Copyright 2012 Gatan Inc. All Rights Reserved.

57

DigitalMicrograph

and scale when that image is moved or scaled.


Generally, annotations which are specific to an image (such as arrows or text pointing
out features, scale markers, or particles) are attached to an image. Annotations which
are not specific to an image (such as a company or site logo) are attached to the
page.
You can change the target easily. See "To set the target in the Target palette".

About images
Images are special objects within DigitalMicrograph. Since one of the primary
purposes of DigitalMicrograph is to deal with images, many operations will act upon
an image object within an image document. For example, there may be four images
contained within an image document. In order to rotate one of them you will have to
select one of the images if you are in page mode and then perform the rotate
command from the menu. If you are in image mode, the image choice will already be
obvious since there will be only one image displayed.

About the Control Palette


Objects can be directly manipulated by using the mouse. For instance, a box can be
resized by dragging and moved with the Pointer tool.
Objects can also be precisely controlled via the Control palette, which changes
according to the object selected. Different objects have different properties and the
Control palette will allow you to manipulate those properties specific to the object
selected.
For example, when a line is selected, controls are provided for the x and y positions of
the line, the length of the line, the inclination of the line, and the anchor point of the line
(the square depicted on the line).

1.4.1

Manipulating Annotations

Manipulating Annotations
You will need to manipulate objects, such as images and annotations, in order to print or
otherwise present your data.

To select objects
When you have multiple objects within an image window and you want to manipulate
one of them (for example delete it), you will need to select the desired objects.
You select objects in two different ways.
To select a single object, click on the object with the Pointer tool.
To select multiple objects, drag around the objects with the Pointer tool.
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

58

You can extend the current set of selected items by holding down the Shift key while
selecting a new item.
You can reduce the current set of selected items by holding down the Shift key while
selecting an already selected item.

To move objects
Many objects can be directly moved. Other objects are intrinsically associated with an
image (such as a Fourier or particle mask) and cannot be directly moved. Be careful
not to drag any of the green handles on an object since that will change the object
instead of moving it (it may change the size of a box, for instance).
To move objects, click and drag the object with the Pointer tool.
To move multiple objects, first select and then drag the objects with the
Pointer tool.
Objects can also be moved to other image documents or to another application.
When you drag an object outside of its image document window, it will change to an
outline and you can drag this outline to other applications and other image document
windows (see "To drag and drop objects").

To move the target image display in page mode


Images are treated specially in some cases. Since objects can be attached to images
and you may want to manipulate those objects directly, DigitalMicrograph locks the
target image display in place to prevent accidentally moving it. (See "About Targets"
for more information.)
To move the target image display when you are in page mode, drag the
image with the Pointer tool using the right mouse button.
You can also temporarily change the target to be the page instead of the image in
order to move a particular image (see "To set the target in the Target palette").
In image mode, the image cannot be moved with respect to the page.

To manipulate objects using the mouse


Manipulating an object means changing anything about it other than its position on the
page. For instance, changing the size of a box.
Many objects can be directly manipulated. Other objects can only be moved and still
others can only be selected and not be changed or moved.
To manipulate an object, click and drag one of the green handles with the
Pointer tool.

Copyright 2012 Gatan Inc. All Rights Reserved.

59

DigitalMicrograph

What happens when you drag one of the handles on an object depends on the object.
Dragging on any of the four handles of a box annotation will change the size of the
box. Dragging on any of the four handles of a text annotation will only move the text
annotation. The size of a text annotation is determined by the size of the font and this
is set through a menu.

To change an image's placement through the Image Display Info dialog


You can change the placement of an image by using the Image Display Info dialog.
1. Switch to page mode using the target palette.
2. Select an image for which you want to set the placement.
3. Choose Image Display under the Display menu.
4. Select Display->Placement on the left side of the dialog box.
The Placement panel will appear in the right side of the dialog box.
5. Enter the desired X and Y positions.
6. Click OK.

To change the front-to-back ordering of objects


You can change the front-to-back ordering of objects.
1. Select the objects for which you want to change the ordering.
2. Choose Send Behind or Bring to Front from the Display menu.
Only items attached to a common object can be sent to the back or brought to
the front together.
The ordering is within the parent object. For instance, annotations attached to an
image will always be in front of the image. To send the annotations behind the image,
detach them from the image and change the ordering once they are attached to the
page.

To group objects
You can group objects together.
1. Select the objects you want to group together.
Grouped objects must all belong to the same parent. The resulting group will
belong to the same parent.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

60

2. Choose Group from the Display menu.


The objects will now be grouped together.
Grouped objects can only be manipulated and moved as a unit. The individual objects
within the group cannot be manipulated directly. To manipulate the individual objects
directly, ungroup the group.

To ungroup objects
You can ungroup objects that have been previously grouped.
1. Select the groups you want to ungroup.
2. Choose Ungroup from the Display menu.
The resulting individual objects will belong to the parent that the group
belonged to. For instance, ungrouping a group attached to an image will result
in the individual objects being attached to the image.

To attach an object to an image


You can detach an object attached to a page and re-attach it to an image.
1. Select the objects you want to attach to an image.
The objects must initially be attached to the page.
2. Select the image to which you want to attach the objects.
You will have to hold down the Shift key to make the additional selection.
3. Choose Attach from the Display menu.
The objects will now be attached to the selected image. If multiple images are
selected (which means you are attaching one image to another), the rearmost selected image will be used as the new parent for the image and
objects.

To detach an object
You can detach an object attached to an image and re-attach it to its page.
1. Select the objects attached to an image.
If multiple objects are selected, they must all be attached to the same image.
2. Choose Detach from the Display menu.

Copyright 2012 Gatan Inc. All Rights Reserved.

61

DigitalMicrograph

The objects will now be attached to the page.

To align objects
You can align multiple objects to one another.
1. Select the objects you wish to align.
The objects must be attached to the same parent.
2. Choose the desired alignment from the Align submenu under the Display menu.
3. You can align horizontal centers, vertical centers, or both.

1.4.2

Editing Annotations

Editing Annotations
DigitalMicrograph provides many standard methods for moving objects between image
documents and to other applications.

To copy and paste objects


You can use the Cut and Paste method to move objects from one image document to
another image document, from an image document to another application, or from
another application to an image document.
1. Select the objects you want to copy.
2. Choose Copy from the Edit menu.
3. Click on the title bar of another image document or switch to another application.
You can skip this step to copy an exact duplicate of the selected objects into
the current image document.
4. Choose Paste from the Edit menu.
The objects will be pasted into the selected image document or application.

To drag and drop objects


You can use the Drag and Drop method to move objects from one image document
to another image document, from an image document to another application, or from
another application to an image document.
Drag the desired objects with the Pointer tool to another window.
The drag will begin when the object leaves the window. The object will turn into
an outline. You can drop this outline in other windows or back in the same
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

62

window. If you drop it back in the same window, it will move the object to the
new location.
An image displayed in image mode (as opposed to Page mode) or an image as the
default target in Page mode, can be dragged by holding down the right mouse button.

To cut and clear objects


You can use the Cut and Delete method to remove objects from an image document.
1. Select the objects you want to cut or delete.
Cutting stores the object in the clipboard until you paste it or copy or cut
something else.
2. Choose Cut or Clear from the Edit menu.
You can also press the Delete key to delete objects.
The objects will be deleted from the image document.

1.4.3

About Targets

About Targets
Objects are always attached to a parent. The default parent is called a target. The target can
be either the page or an image on the page. If you are in image mode, the target is always the
image. If you are in page mode, you can select either the page or the image as the target.
Objects attached to the page are independent from the images and move and scale with the
page.
Objects attached to images move and scale with that image, but are independent from the
other images on the page.

To set the view mode in the Target palette


You can switch from page mode to image mode in the Target palette.

Click on the radio button to the left of "Page" to switch to page mode.
Click on the radio button to the left of the image that you want to switch to
Copyright 2012 Gatan Inc. All Rights Reserved.

63

DigitalMicrograph

image mode.

To set the target in the Target palette


You can set the default target using the Target palette.
1. Switch to page mode using the Target palette.
You must be in page mode to select the target.
2. Click on the text "Page" to target the page.
If the page is the selected target, a dark border will appear around the page.
3. Click on the text "Image" for the image you want to target.
If an image is the selected target, the handles of the image will flash.
The selected target will be displayed in bold type in the Target palette.

1.4.4

Setting Object Information

Setting Object Information


DigitalMicrograph stores extra information with some objects. This information is used by
scripts and operations performed on the object. You can access this information via the
Image Display Info dialog.

To edit an object's tags


You can directly edit an object's tags. Editing tags is a very advanced use of
DigitalMicrograph and should in general not be done unless you have explicit
instructions on how to do so. It is possible to make images unloadable by editing tags.
1. Select the object whose tags you want to edit.
2. Choose Object from the Display menu.
The Image Display Info dialog will appear.
3. Select Object->Tags on the left side of the dialog box.
The Tags panel will appear in the right side of the dialog box.
4. Enter the information in the right portion of the dialog box.
A list of tags is displayed. You can use the twist-down controls to open up groups and
lists of tags.
Edit

Click this button to edit the selected tag


Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

Add
Remove

64

Click this button to add a new tag


Click here to remove the selected tag

5. Click OK.
Switching to a different panel will automatically save your choices.

To edit an object's other properties


Some objects will have additional properties that can be edited using the Image
Display Info dialog.
1. Select the object whose properties you want to edit.
2. Choose Image Display from the Display menu.
The Image Display Info dialog will appear.
3. Select the desired property panel along the left side of the dialog.
The selected panel will appear in the right side of the dialog box.
4. Edit the properties.
5. Click OK.
Switching to a different panel will automatically save your choices.

1.4.5

Annotations

Annotations
You can add annotations such as rectangles, ovals, lines, arrows, and text to an image
document. Annotations will be attached to the selected target by default. You can detach or
attach them as desired.

To add an annotation
You can use the tools in the Standard Tools palette to add annotations.
1. Select the desired tool from the Standard Tools toolbar.
You can choose the Text, Line, Rectangle, or Oval tool.

Copyright 2012 Gatan Inc. All Rights Reserved.

65

DigitalMicrograph

2. Click and drag in the image using the selected tool.


If you add a text annotation, start typing your text after the first click with the
tool.
To create an arrow, use the Line tool, while holding down the Ctrl key for a
double arrow, or the Alt key for a single arrow.
To create a Square, use the Rectangle tool, while holding down the Shift key.
To create a Circle, use the Oval tool, while holding down the Shift key.
3. Adjust the display of the annotation to suit your preferences.
Methods for adjusting the display of the annotation are covered below.

To precisely place rectangles and ovals


You can precisely view and edit the position of rectangles and ovals using the Control
palette. Add the Control palette using Windows::Floating Palettes::Control.
Select the desired rectangle or oval and edit it using the Control palette.
You can view and edit the x and y positions and the width and height using the Control
palette.
The X and Y controls display the calibrated coordinates of the anchor point of the
rectangle or oval. The calibrated coordinates are in terms of the parent of the
rectangle or oval object.
The W and H controls change the width and height while holding the anchor point
constant.
The large square on the box at the upper left of the Control palette is the anchor point
of your annotation. This determines the point at which your rectangle is anchored
when enlarged or reduced. You can change the anchor point by clicking on any other
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

66

control point on the box.

To precisely place lines and arrows


You can precisely view and edit the position of lines and arrows using the Control
palette, found in Windows::Floating Palettes::Control.
Select the desired line and edit it using the Control palette.

You can view and edit the x and y positions, the length, and the rotation of the line
using the Control palette.
The X and Y controls display the calibrated coordinates of the anchor point of the line.
The calibrated coordinates are in terms of the parent of the line object.
The L control changes the length of the line while holding the anchor point constant.
The R control changes the rotation of the line while holding the anchor point constant.
You can change the anchor point by clicking on different control points on the line
annotation.

To change an annotation's background


Annotations can be drawn using different colors. All annotation have a Foreground
Color and a Background Color which can be set using the matching items in the
Display menu. Furthermore, boxes and ovals can be filled or unfilled.
1. Select the annotation for which you want to change the color.
2. Choose Set Foreground Color... or Set Background Color... under the Display
menu. The following dialog will be displayed:

Copyright 2012 Gatan Inc. All Rights Reserved.

67

DigitalMicrograph

Choose the color you want, and hit OK.


3. Choose Background under the Display menu, and select Filled or Not Filled.

To change a text annotation's font, size, style and alignment


You can also change the font, font size, or style of text annotations.
1. Select the text annotation you wish to change.
2. Choose Font... under the Display menu. The following dialog will be displayed:

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

68

In this dialog select the Font, the Font style and the Size.
5. Set the text alignment by choosing the desired alignment from the Text Alignment
submenu under the Display menu.
Text alignment refers to how the text is aligned within the annotation. It will only
apply to text annotations spanning multiple lines.

1.5

Image Processing and Analysis


Image Processing and Analysis
DigitalMicrograph provides many tools for analyzing and processing images. This chapter
describes how to use the analysis and processing tools specific to DigitalMicrograph. For a
more general discussion of image processing, consult an image processing textbook, such
as The Image Processing Handbook by John C. Russ.

1.5.1

Using Regions of Interest

Using Image Regions of Interest


Many times, in order to process or analyze an image, you will need to select a region of
interest (ROI) on an image. The region of interest indicates the part of the image your are
interested in processing or analyzing.
Methods of selecting regions of interest are specific to the type of image display the image is
displayed as.
Copyright 2012 Gatan Inc. All Rights Reserved.

69

DigitalMicrograph

The ROI Tools provides a set of tools for indicating regions of interest.

To specify a rectangular region of interest on an image with a Raster or


RGB display
You can make a rectangular region of interest on an image displayed with the Raster
or RGB image display type.
Use the Rectangle ROI tool to make a region of interest.
Making a region of interest will erase all previous regions of interest. To extend
an existing set of regions of interest, hold down the Shift key while making the
new region of interest.
Hold down the Shift key while making a rectangular region of interest to restrict
it to be a square.
Hold down the Alt key while making a rectangular region of interest to restrict it
to be a rectangle with a side that is a power of two (useful when performing
FFTs).
The region of interest will appear as a red-dashed rectangle.

To specify a line of interest on an image with a Raster or RGB display


You can make a line of interest on an image displayed with the Raster or RGB image
display type.
Use the Line ROI tool to make a line of interest.
Making a line of interest will erase all previous regions of interests. To extend
an existing set of regions of interest, hold down the Shift key while making the
new region of interest.
Hold down the Shift key while drawing a line of interest to restrict it to 45 or
90.
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

70

The region of interest will appear as a red-dashed line.

To specify a point of interest on an image with a Raster or RGB display


You can specify a point of interest on an image displayed with the Raster or RGB
image display type.
Use the Point ROI tool to make a point of interest.
Making a point of interest will erase all previous regions of interest. To extend
an existing set of regions of interest, hold down the Shift key while making the
new region of interest.
The region of interest will appear as a red cross-hair.

To specify a closed-loop region of interest on image with a Raster or


RGB display
You can specify a closed-loop region of interest on an image displayed with the
Raster or RGB image display type.
Use the Closed-Loop tool to make a closed-loop region of interest.
Making a closed-loop region of interest will erase all previous regions of
interest. To extend an existing set of regions of interest, hold down the Shift
key while making the new region of interest.
The region of interest will appear as a red-dashed region.

To specify an open-line region of interest on an image with a Raster or


RGB display
You can specify an open-line region of interest on an image displayed with the Raster
or RGB image display type.
Use the Open-Line tool to make an open-line region of interest.
Making an open-line region of interest will erase all previous regions of interest.
To extend an existing set of regions of interest, hold down the Shift key while
making the new region of interest.
The region of interest will appear as a red-dashed line.

To adjust a region of interest on an image with a Raster or RGB display


Copyright 2012 Gatan Inc. All Rights Reserved.

71

DigitalMicrograph

Regions of interest are just additional objects attached to images. You can move
them around as desired. You can also select, deselect, copy, drag, and delete them.
You can edit rectangular and line regions of interest.
Edit rectangle and line regions of interest by dragging their handles.
Hold down the Shift key while changing a rectangular region of interest to
restrict it to be a square.
Hold down the Alt key while changing a rectangular region of interest to restrict
it to be a rectangle with a side that is a power of two (useful when performing
FFTs).
Hold down the Shift key while changing a line of interest to restrict it to 45 or
90.

To specify a region of interest on an image with a line plot display


You can specify region of interest on an image displayed in the Line Plot image
display type.
If the line plot is the target, use the Pointer tool to make a region of interest.
If the line plot is not the target, use the Rectangular ROI tool to make a region of
interest.
Making a region of interest will erase all previous regions of interest. To extend
an existing set of regions of interest, hold down the Shift key while making the
new region of interest.
The region of interest will appear as a colored rectangle on the line plot.

To adjust a region of interest on an image with a line plot display


You can edit existing regions of interest on a line plot.
1. Make the line plot the target for the image document.
See "Adjusting a Target".
2. Use the Pointer tool to drag the sides of a region of interest.
Start the drag on one of the sides of the region of interest.
3. Use the Pointer tool to move an entire region of interest.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

72

Start the drag in the middle of the region of interest.


4. Use the Pointer tool to drag on the region of interest badge to access a region of
interest lying beneath other regions of interest.
5. Use the left or right arrow keys to move the region of interest.
6. Use the up or down arrow keys to extend or shrink the region of interest.
The right side of the region of interest is adjusted in the process.
Some regions of interest may be marked as unmovable. You cannot move these
regions of interest. The application that created them (such as Spectrum Imaging) will
be responsible for moving them, if necessary.

To delete a specific region of interest on an image with a line plot display


You can delete specific regions of interest on a line plot.
1. Switch to image mode with the desired line plot as the image.
2. Select the regions of interest that you wish to delete by clicking on their badges (the
+ marks).
The badge will turn into a solid square when it has been selected.
3. Use the Shift key to select or deselect additional regions of interest.
4. Type the Backspace or Delete key.
Some regions of interest may be marked as undeletable. They will appear as solid
rectangles. You cannot delete these regions of interest. The application that created
them (such as Spectrum Imaging) must delete them.

To make a region of interest on an image with a Spreadsheet display


You can also make rectangular regions of interest on images with Spreadsheet
displays.
1. Make the Spreadsheet image display the target for the image document.
See "Adjusting a Target".
2. Use the Pointer tool to make a region of interest.
Drag with the Pointer tool to select the desired cells.

Copyright 2012 Gatan Inc. All Rights Reserved.

73

1.5.2

DigitalMicrograph

Using Line Profiles

Using Line Profiles


You can use a line profile to sample an image along a line and display the sampled
data in a line plot. The line plot will represent the data in the source image even if the
source data changes or the line-profile position changes in the source image.
You can only create line profiles on images with a Raster display.
You can also integrate the original source data perpendicularly to the line profile. See "
To adjust the integration width of a line profile".
For more information on manipulating the Line Plot generated see "Using Line Plot
Image Displays".

To create a line profile


You can only create a line profile on an image with a Raster display.
Use the Line Profile tool to create a line profile.
A new Line Plot window will be created that represents data sampled from the source
image beneath the line profile.

To adjust the endpoints of a line profile


You can adjust the endpoints of a line profile by two methods.
Adjust the endpoints by dragging the handles on the line profile.
Adjust the endpoints by double-clicking on the line profile.
The Change Profile Info dialog will appear. Enter the desired coordinates in this dialog.
The coordinates should be specified in uncalibrated units (i.e. pixels).

To adjust the integration width of a line profile


You can adjust the integration width of a line profile by two methods.
Adjust the integration width by selecting the line profile and pressing the '+'
and '-' keys.
Adjust the integration width by double-clicking on the line profile.
The Change Profile Info dialog will appear. Enter the desired integration width in this
dialog. The line profile will change to reflect the integration width.
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

1.5.3

74

Using Calibrations

Using Calibrations
DigitalMicrograph allows you to calibrate an image so that the row, column, and intensity
correspond to physical values. Calibrations can be performed using the Image Display Info
dialog or using a line of interest.
The calibration uses two numbers, offset and scale, to translate each dimension to a
corresponding physical value. For instance, an image that is 1000 pixels wide could be
calibrated so that each pixel corresponded to 3 nm (scale) and the left-most pixel could
represent 42 nm (negative offset). The right-most pixel would then represent 3042 nm.
In addition to the two numbers, offset and scale, you need to enter the units.

To enter or see an image's calibration using Image Display Info dialog


You can enter or view an image's calibrations.
1. Select the image on which to view and edit calibrations.
2. Choose Image Display under the Display menu.
3. Select Image::Calibration on the left side of the dialog box.
The Calibration panel will appear in the right side of the dialog box.
4. Enter the scale, origin, and units for the intensity, if desired.
5. Enter the scale, origin, and units for each of the dimensions.
Typically, the scale and units for each of the dimensions should match each
other on Raster image displays.
6. Click OK.

To disable/enable an image's calibration in the Target palette


You can enable or disable an image's calibration. If the calibration is disabled, all
coordinates will be displayed in units of pixels.
1. Select the image for which you want to enable or disable calibration in the Target
palette.

Copyright 2012 Gatan Inc. All Rights Reserved.

75

DigitalMicrograph

2. Click on the Ruler to disable or enable calibration.


The Ruler will turn to a flat line to indicate no calibration.

To disable/enable an image's calibration using the Object Info Window


1. Select the image on which you want to enable or disable calibration.
2. Choose Image Display under the Display menu.
3. Select Image->Calibration on the left side of the dialog box.
The Calibration panel will appear in the right side of the dialog box .
4. Check or uncheck the Display Calibrated Units check box at the bottom.
5. Click OK.

To calibrate from a line of interest


You can calibrate an image's dimensions by using a line of interest.
1. Draw a line of interest on the image you wish to calibrate using the Line region of
interest tool.
2. Select the line of interest.
Click on it once or until the green handles appear.
3. Choose Calibrate from the Analyze menu.
The Calibration dialog will appear.
4. Choose the units in which to calibrate the image.
You can also enter a custom unit in the Other field.
5. Enter the length of the line in calibrated units.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

76

6. Enter the geometric correction factor between the x and y directions.


This should typically be set to "1", corresponding to the same calibration in the
x and y directions.
7. Click OK.
The image will now be calibrated according to the information you entered.

To calibrate automatically
Some acquisition plug-ins will automatically calibrate the image when you acquire an
image. Follow the instructions for the particular acquisition plug-in in order to calibrate
automatically.

To add a scale marker to a Raster or RGB image


DigitalMicrograph can draw a scale marker on any calibrated image that is displayed
as a Raster or RGB display type.
1. Select the image to which you want to add the scale marker.
2. Choose Add Scale Marker from the Edit menu.
The scale marker will appear on the image.

To resize a scale marker on a Raster or RGB image


The scale marker can be resized as desired.
Click on the scale marker and drag by the handles to resize.

To move a scale marker on a Raster or RGB image


The scale marker can be moved as desired.
Click on the scale marker and drag it to relocate.

1.5.4

Using the Slice Tool

Using the Slice Tool


Some applications, such as Spectrum Imaging, require the use of a three-dimensional
image, rather than the standard two-dimensional image. DigitalMicrograph gives you a control
to choose which layer (slice) of the three-dimensional dataset to display as the image.

Copyright 2012 Gatan Inc. All Rights Reserved.

77

DigitalMicrograph

To change the slice of the data


1. Select Floating Windows::Slice under the Window menu.
This will open the Slice floating window.

2. Select the three-dimensional image for which you want to change the slice.
The Slice window will be disabled if the data is not three dimensional.
3. Drag the top slider to adjust the slices displayed.
4. Drag the bottom slider to adjust the number of slices to be integrated and displayed
simultaneously.
5. Check the Display Center check box to show all coordinates with respect to the
center.

1.5.5

Image Processing

Overview of Image Processing


DigitalMicrograph supports many types of image processing. This manual
covers the basic types of image processing, including changing data types
, image transformations, filtering, convolutions and Fourier Processing.
1.5.5.1

Changing Data Types

Changing Data Types


Each image is stored as a set of numbers arranged into rows and columns. Each number is
stored in memory in a specific format called the data type. You can change the data type by
which each image is stored. Data types may be narrow (able to store a small range of
numbers) such as integer data types or wide (able to store a large range of numbers) such
as the real data types. Additionally, data types may store more than one value, e.g., complex,
or RGB.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

78

To change an image's data type


You can change an image's data type.
1. If you are viewing the image document in page mode, select the image of which
you want to change the data type.
2. Choose Change Data Type under the Edit menu.
A dialog will appear allowing you to select the new data type.
3. Select the new data type in the pop-up menu.
You can choose Binary, Integer, Real, Complex, or RGB.
4. Select options for the new data type.
The Integer data type will allow you to select signed or unsigned data.
The Integer, Real, and Complex data types will allow you to select the number
of bytes used for the data.
DigitalMicrograph displays the range, smallest value, and other information
about the data type in the dialog also.
5. Click OK.
The data type of the image will change.

To convert to one-byte unsigned data


When you convert any data type to one-byte unsigned integer data, DigitalMicrograph
will ask you whether you want to clip or scale the data.
When the data is clipped, all values above 255 will be set to 255 and all values below
0 will be set to 0.
When the data is scaled, DigitalMicrograph will map the maximum value in the original
image to 255, the minimum value in the original image to 0, and values in between
linearly to the range of 0 to 255.
1. Follow the steps to change an images data type.
See "To change an image's data type".
2. Select integer, one byte, unsigned data.
A dialog asking whether to scale or clip will appear after you click OK.
Copyright 2012 Gatan Inc. All Rights Reserved.

79

DigitalMicrograph

3. Select the desired conversion method.


4. Click OK.
The data type will be changed as specified.

To convert from complex data


When you convert from complex to another data type, DigitalMicrograph will ask you
how to convert the data. You have the choice of using the real, imaginary, modulus,
log of modulus, or phase of the complex data.
1. Follow the steps to change an image's data type.
See "To change an image's data type". Your original data should be complex.
2. Select new data type.
A dialog asking you for the complex conversion method will appear after you
click OK.
3. Select the desired conversion method.
4. Click OK.
The data type will be changed as specified.

To convert to RGB data


When you convert from any data type to RGB, DigitalMicrograph will scale the data so
that it fits into RGB data range of 0 to 255. In the resulting image the red, green, and
blue components will all have the same value.

To convert from RGB data


When you convert from RGB to another data type, DigitalMicrograph will ask you how
to convert the data. You have the choice of using the red, green, blue, or brightness
value of the RGB data.
1. Follow the steps to change an images data type.
See "To change an image's data type". Your original data should be RGB.
2. Select new data type.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

80

A dialog asking you for the RGB conversion method will appear after you click
OK.
3. Select the desired conversion method.
4. Click OK.
The data type will be changed as specified.

To build an RGB image from three images


You can construct a new RGB image based on three source images representing the
red, green, and blue components. The three source images must contain either real
or integer data.
1. Choose Construct RGB Image under the Edit menu.
A dialog will appear asking for the three source images.
2. Select the three images to use as the red, green, and blue components.
The sources images must all be the same size and must be open. The data in
the source images is mapped to a range of 0 to 255 by using the contrast
limits used in the respective images. Changing the contrast limits of the
source images will change the appearance of the resulting RGB image (see "
About Contrast Limits").
You can select the same image for more than one component of the RGB
image.
3. Click OK.
A new RGB image will be created using the three selected source images.
1.5.5.2

Using Image Transformations

Using Image Transformations


Image transformations include flipping, rotating, scaling, and resampling an image. These
transformations are covered in this section.

To flip an image
You can flip an image horizontally or vertically.
1. If you are viewing the image document in page mode, select the image you want to
flip.

Copyright 2012 Gatan Inc. All Rights Reserved.

81

DigitalMicrograph

2. Choose Flip Horizontal or Flip Vertical from the Edit menu.


The image will be flipped in the direction you specified.

To rotate an image by 90
You can rotate an image by 90 in either direction (right or left).
1. If you are viewing the image document in page mode, select the image you want to
rotate by 90.
2. Choose Rotate Right or Rotate Left from the Edit menu.
The image will be rotated in the direction you specified.

To rotate an image by an arbitrary angle


You can rotate an image by an arbitrary angle. The resulting image will be larger than
the original image. The areas in the resulting image that map to locations outside of
the original source image will be set to zero.
1. If you are viewing the image document in page mode, select the image you want to
rotate by an arbitrary angle.
2. Choose Rotate under the Process menu.
A dialog will appear asking for the angle of rotation and the direction of rotation.
3. Enter the angle and direction of rotation.
4. Click OK.
The image will be rotated as you specified.

To scale an image
You can scale an image to a different size. Scaling involves resampling the data. You
can resample the data in different ways.
1. If you are viewing the image document in page mode, select the image you want to
scale.
2. Choose Scale under the Process menu.
A dialog will appear asking for the new image size and resampling method.
The bottom of the dialog will display the memory requirements for the new
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

82

image.
3. Choose whether you want to constrain the proportions.
If you constrain proportions, the new image will have the same proportions as
the source image.
4. Choose whether to specify each dimension by pixels or by percentage of source
image dimension.
5. Enter the new dimensions.
If the proportions are constrained, you only need to enter one of the
dimensions (the other will be calculated for you).
6. Select the resampling method, either Bilinear or Nearest Neighbor.
You can choose Bilinear so that pixels in the new image that map in between
pixels in the source image will be found by bilinear interpolation of the fourpixels units around the pixel in the source image. You can choose Nearest
Neighbor so that pixels in the new image that map in between pixels in the
source image will be found by taking the nearest pixel to a pixel in the source
image.
7. Click OK.
A new image will be created as specified.

To re-bin an image by a factor of two


You can perform a re-binning of the image to reduce its size by two. This involves
summing up four pixels to make a single pixel for each four pixels in the source
image.
1. If you are viewing the image document in page mode, select the image you want to
re-bin by two.
2. Choose Re-bin by Two under the Process menu.
The images will be re-binned.
The size of the image will be one half of what it was before. The display will remain
the same size. This operation automatically increases the zoom factor on Raster and
RGB image displays by two.
1.5.5.3

Using Filtering

Using Filtering

Copyright 2012 Gatan Inc. All Rights Reserved.

83

DigitalMicrograph

DigitalMicrograph supplies several types of image filters. Image filters are divided into two
major categories: spatial and non-linear.

About Spatial Filters


Spatial filters primarily create a new image based on a linear combination of pixels in
the same general neighborhood in the original image. A convolution is an example of a
spatial filter. DigitalMicrograph includes several convolutions in the spatial filter menu.
For general convolutions, see "Using Convolutions".

About Non-linear Filters


Non-linear filters create a new image based on non-linear algorithm applied to pixels in
the same general neighborhood in the original image. An example of a non-linear filter
is the minimum filter, which takes the pixel with the minimum intensity in a
neighborhood in the source image.

To apply a sharpening filter


Sharpen is used primarily to increase the brightness at edges and boundaries. The
Sharpen filter is a convolution with the following kernel:

1. If you are viewing the image document in page mode, select the image you want to
sharpen.
2. Choose Sharpen from the Spatial Filter submenu under the Process menu.
A new image will be created that is the sharpen-filtered image of the original.

To apply a smoothing filter


Smoothing is used primarily to reduce visible noise. The Smooth filter is a convolution
with the following kernel:

1. If you are viewing the image document in page mode, select the image you want to
smooth.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

84

2. Choose Smooth from the Spatial Filter submenu under the Process menu.
A new image will be created that is the smooth-filtered image of the original.

To apply a Laplacian filter


The Laplacian is used for more advanced edge finding. The Laplacian filter is a
convolution with the following kernel:

1. If you are viewing the image document in page mode, select the image for which
you want to enhance the edges.
2. Choose Laplacian from the Spatial Filter submenu under the Process menu.
A new image will be created that is the Laplacian-filtered image of the original.

To apply a Sobel filter


The Sobel filter is a gradient operator used for edge and direction finding. The Sobel
filter is a convolution with the following kernels:

Both kernels are applied to the source image and the resulting two images are
combined by taking the square of each, adding them together, and then taking the
square root of the result.
1. If you are viewing the image document in page mode, select the image for which
you want to enhance the edges.
2. Choose Sobel from the Spatial Filter submenu under the Process menu.
A new image will be created that is the Sobel-filtered image of the original.

To apply a non-linear filter


DigitalMicrograph implements 5 different non-linear filters. For each filter the software
cycles through an image and looks at a small neighborhood of pixels.

Copyright 2012 Gatan Inc. All Rights Reserved.

85

DigitalMicrograph

Median
The median of the values in the neighborhood is used in the destination image.
This filter is a type of smoothing filter.
Minimum
The minimum of the values in the neighborhood is used in the destination
image. This filter is used to eliminate bright objects.
Maximum
The maximum of the values in the neighborhood is used in the destination
image. This filter is used to eliminate dark object.
Range
The difference between the minimum and the maximum of the values in the
neighborhood is used in the destination image. This filter can be used to find
edges of features, or to distinguish textures.
Midpoint
The average of the minimum and the maximum of the values in the
neighborhood is used in the destination image. This filter is a type of
smoothing filter.
You can specify the size and shape of the neighborhood used in the calculations.
1. If you are viewing the image document in page mode, select the image on which
you want to perform median filtering.
2. Choose a filter from the Non-Linear Filter submenu under the Process menu.
A dialog will appear asking for the size and shape of the filtering window.
3. Select the desired neighborhood window shape.
The shape can be either a horizontal line, vertical line, cross, or entire
neighborhood.
4. Select the desired neighborhood size.
The larger the size, the slower the operation.
5. Click OK.
A filtered image will appear.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

1.5.5.4

86

Using Convolutions

Using Convolutions
Spatial convolution is an operation in which each pixel in an image is replaced with a
weighted sum of its surrounding pixels. The array of weights for each of the surrounding
pixels is called a kernel. The square root of the number of surrounding pixels used is called
the size of the kernel.
In "Using Filtering" some pre-built convolutions were shown, such as Sharpen, Smooth,
Laplacian and Sobel. In that section the kernels used in the convolution could not be
modified.
DigitalMicrograph provides a number of built-in kernels that you can use when processing
images. You can also add your own kernels.

To perform a convolution on an image


You can perform a convolution on any image.
1. If you are viewing the image document in page mode, select the image on which to
perform the convolution.
2. Choose Convolution from the Spatial Filters submenu under the Process menu.
A dialog asking you for the convolution kernel will appear.
3. Select a kernel and variation from the menus.
DigitalMicrograph provides a number of basic kernel types.
4. Modify the kernel by entering values in the edit fields.
You can skip this step if the existing kernel is satisfactory.
5. Click OK.
A new image with the kernel applied to the selected image will appear.

To add a custom kernel


You can add a custom kernel so that it appears in the menus.
1. Select an image.
2. Choose Convolution from the Spatial Filters submenu under the Process menu.
3. Enter your desired kernel.
Copyright 2012 Gatan Inc. All Rights Reserved.

87

DigitalMicrograph

4. Click on the Save As button.


A dialog will appear asking for the type and variation of the kernel.
5. Enter the Type and Variant for the kernel.
The Variant menu will show all kernels with the same type name.
You do not need to enter the size of the kernel; it will be automatically added to
the menus.
6. Click OK.
The kernel will now appear in the type and variation menus of the convolution
dialog.

To remove a custom kernel


You can remove a custom kernel so that it no longer appears in the menus.
1. Select an image.
2. Choose Convolution from the Spatial Filters submenu under the Process menu.
3. Select the Type and Variant of the kernel you want to remove.
4. Click the Remove button.
A dialog confirming your choice will appear.
5. Click OK.
The kernel will no longer appear in the type and variation menus in the
convolution dialog.

To import a kernel
You can import a kernel in a text file into DigitalMicrograph. The kernel in the text file
must have integer numbers arranged into rows of numbers. Each row should be
separated by a Return and each number should be separated by a comma or a
Space.
1. Select an image.
2. Choose Convolution from the Spatial Filters submenu under the Process menu.
3. Click the Import button.
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

88

4. Select the text file you want to import.


5. Enter the type and variant for the kernel.
The variant menu will show all kernels with the same type name.
You do not need to enter the size of the kernel; it will be automatically added to
the menus.
6. Click OK.
The kernel will now appear in the type and variation menus in the convolution
dialog.
1.5.5.5

Using Simple Math

Using Simple Math


DigitalMicrograph provides an easy way to perform simple mathematical operations on
images or pairs of images.

To perform a calculation on an image or images


You can easily specify simple math operations involving one or two images.
1. Choose Simple Math under the Process menu.
A dialog will appear asking you to specify the simple math operation.
2. Select the operation you want to perform.
The operations are mostly self-explanatory. MAX and MIN compute the
maximum and minimum values of the two images. For instance, MAX(a,b)
would replace each pixel in the new image with the maximum pixel from "a"
and "b" at the particular spot in the image.
The operation must involve at least one image. If the operation has a single
image (such as "-a"), you will only need to select a single source image. If the
operation has two images (such as "a+b"), you will need to select a source
image "a" and another source. The second source can be either an image or a
constant number.
3. Select the source image "a."
4. Select the second image "b," if required.
If you want to use a constant value for the second image, enter a constant
value.
Copyright 2012 Gatan Inc. All Rights Reserved.

89

DigitalMicrograph

If you have a second image, select the second image.


5. Click OK.
A new image combining the source images as specified will appear.
All of the Simple Math operations and many others can also be performed using the
scripting language.

1.5.6

Fourier Processing

Fourier Processing
Fourier transforms reveal the periodic contents of images. They are useful for image analysis
and filtering. DigitalMicrograph supports a number of different operations involving Fourier
transforms.
A fast Fourier transform is a special algorithm for quickly calculating a Fourier transform on a
source image having dimensions that are powers of two (i.e. 2, 4, 8, 16, 32, 64, etc.) Armed
with this size requirement, Fast Fourier Transforms (FFTs) are significantly faster than
straightforward calculation of the discrete Fourier transform (DFT).
Using DigitalMicrograph, you can calculate a Fourier transform based on any image (except
RGB images) with the appropriate dimensions. Fourier transforms will also work on
(appropriately sized) regions of interest placed on an image.
The result of a Fourier transform on a real-valued image is a complex image that is Hermitian
in nature. This means that the image is symmetrical around the center (with symmetric
points being complex conjugates of one another). The resulting transform represents the
source image in frequency space.
The result of a Fourier transform on a complex-valued image is another complex image that
is not Hermitian in nature. The resulting transform represents the source image in frequency
space.
You can also perform inverse Fourier transforms, which transform from frequency space to
real space. If the source for the inverse Fourier transform is Hermitian, the result will be a
real-valued image. If the source image is regular complex, the result will be another complexvalued image.

About Packed Data


DigitalMicrograph supports two types of complex data: packed complex and full
complex.
Because of a Fourier transform's Hermitian nature, a Fourier transform on real data
produces a complex data image in which every point (x, y) is equal to the complex
conjugate of the point at (-x, -y). When you perform a Fourier transform on a real
image, the resulting data is stored as packed complex image data.
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

90

Packed complex image data takes up less space in memory because it is "packed" in
a special way so only half of the data is stored. However, packed data is not as easily
managed in memory because special algorithms are needed to unpack the data.
You can change an image stored as packed complex data to full complex data (and
release some of the restrictions placed on the image) by converting its data type to
complex.
1.5.6.1

Using Fourier Transforms

Using Fourier Transforms


To do a forward Fourier transform
You can do a forward Fourier transform.
1. If you are viewing the image document in page mode, select the source image of
which you want to calculate a Fourier transform.
The source image must have dimensions that are powers of two.
You can also create a region of interest on the source image with appropriate
dimensions by holding down the Alt key while drawing the rectangular region of
interest.
2. Select FFT or Reduced FFT from the Process menu.
Reduced FFT will first re-bin the image by two (into a temporary image) and
then do the Fourier transform on the reduced image.
If the source image is a real-valued image, the resulting image will be of packed
complex data type.
If the source image is a complex-valued image, the resulting image will be of regular
complex data type.

To do an inverse Fourier transform


You can do an inverse Fourier transform.
1. If you are viewing the image document in page mode, select the source image of
which you want to calculate an inverse Fourier transform.
The source image must have dimensions that are powers of two.
If the source image is regular complex, you can create a region of interest on
the source image with appropriate dimensions by holding down the Alt key
Copyright 2012 Gatan Inc. All Rights Reserved.

91

DigitalMicrograph

while drawing the rectangular region of interest.


2. Select IFFT from the Process menu.
If the source image is a packed complex image, the resulting image will be realvalued.
If the source image is a regular complex image, the resulting image will be complexvalued.

To attach a live Fourier transform to an acquisition image


During acquisition, you may want to perform a Fourier transform or a reduced-size
Fourier transform on each acquired image. You can do this by setting up a "live"
operation. A "live" image is linked to another image and whenever the source image
changes, the "live" image is updated.
DigitalMicrograph allows you to set up "live" Fourier transforms or "live" reduced-size
Fourier transforms during acquisition.
1. Start acquiring an image.
2. Choose FFT or Reduced FFT from the Live submenu under the Process menu.
A live FFT will be set up and recalculated whenever the acquired image's data is
changed.

To do a live Fourier transform on a ROI


You can attach a live Fourier transform to an ROI. The Fourier transform will update
when you move the ROI or when the image data changes.
1. If you are viewing the image document in page mode, select the source image.
2. Create a rectangular region of Interest on the image.
Hold down the Alt key while drawing the region of interest, so that the
dimension will become a power of two.
3. Select FFT or Reduced FFT from the Live submenu under the Process menu.
Moving the ROI will cause a recalculation of the FFT.
1.5.6.2

Auto-Correlations

Auto-Correlations
Auto-correlation is useful for quantifying the resolution attained in an image and for
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

92

determining the self-similarity of an image. DigitalMicrograph performs auto-correlation of real


data in the following way:
1. It performs a Fourier transform of the real image.
2. It multiplies the resulting image by its complex conjugate.
3. It calculates an inverse Fourier transform of the resulting image.
4. It normalizes the resulting image so that its maximum is 1.
Auto-correlation can only be performed on images or selections that have dimensions
that are powers of 2 (i.e., 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, etc.). The resulting
image has floating point data.

To auto-correlate an image
You can calculate an auto-correlation of an image.
1. Click on your image.
The source image must have dimensions that are powers of two.
2. Select Auto Correlation from the Process menu.
The auto-correlated image will appear.
1.5.6.3

Cross-Correlations

Cross-Correlations
Cross-correlation is useful for determining how similar two images are and for determining
how much an image has shifted with respect to another image (in the case of a time
sequence, for instance). DigitalMicrograph performs cross-correlation in the following way:
1. It performs a Fourier transform on each of the two source images.
2. It multiplies the Fourier transform of the first image by the complex conjugate of Fourier
transform of the second.
3. It calculates the inverse Fourier of the resulting image.
A cross-correlation with the same input images is equivalent to an auto-correlation.

To cross correlate two images


You can do a cross-correlation of two images.

Copyright 2012 Gatan Inc. All Rights Reserved.

93

DigitalMicrograph

1. Select Cross Correlation from the Process menu.


A dialog will appear asking for the two input images.
The source images must have dimensions that are powers of two and must
be the same size.
If the source images contain a region of interest, this region of interest is used,
instead of the complete image.
2. Click OK.
A new image will appear that is the cross-correlation of the two source
images.

To cross correlate different areas of the same image


You can cross correlate two different parts of the same image.
1. Create a region of interest on the image.
Hold down the Alt key, so that you create a region of interest with size equal to
a power of two.
2. Copy and paste the image within the region of interest to a new image.
Do this by choosing Copy under the Edit menu and then choosing Paste under
the Edit menu while holding down the Alt key.
3. Create another region of interest on the first image.
Or move the existing region of interest to a different location.
4. Cross correlate the new image with the region of interest on the original image.
Follow the steps for cross-correlation explained above.
1.5.6.4

Using Fourier Masking

Using Fourier Masking


Fourier masking can remove unwanted noise or enhance periodic elements of an image. The
masking is done in frequency space.
The typical sequence for using masking is to perform a Fourier transform on a real-space
image, mask off the desired frequencies in frequency space, and finally perform an inverse
Fourier transform on the masked image.
The mask is created using the Masking tools. Applying them in different sequences can serve

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

94

to combine or exclude different frequencies present in the image.


DigitalMicrograph provides four types of masks for use on frequency space images: Twin
Oval, Band Pass, Periodic, and Wedge.
All masks are symmetric about the origin, because then the data will stay Hermitian when
applying the mask. End therefore the inverse transform will give a real image. The origin of
the image is determined by the calibration of the image. An image created by an FFT
operation is calibrated so the origin is at the center of the image. Images created by other
means might not have appropriate origins set, so you must set them manually (see "Using
Calibrations").

To add a Twin Oval mask


The Twin Oval mask puts a symmetric pair of oval masks upon the image. The
position of the masks can be changed by clicking on the mask and dragging (moving
one also moves the other one since the Fourier transform must remain symmetric).
The masks can be sized and shaped using the selection handles provided.
1. If you are viewing the image document in page mode, select the image to which
you want to add a Twin Oval mask.
2. Click on the image with the Twin Oval mask tool.
Two symmetrically positioned oval masks will appear where you clicked.
Changing one of the masks will symmetrically change the other one also.
3. Adjust the position of the twin ovals.
4. Adjust the shape of the twin ovals.
Hold down the Shift key to force them to be circles rather than ovals.

To add a Band Pass mask


The Band Pass mask puts a pair of circular rings upon the image. The area between
Copyright 2012 Gatan Inc. All Rights Reserved.

95

DigitalMicrograph

the rings is the mask. The two rings are always centered about the center of the
Fourier transform, but the radius of each of the rings can be changed by dragging
their selection handles.
1. If you are viewing the image document in page mode, select the image to which
you want to add a Band Pass mask.
2. Click on the image with the Band Pass mask tool.
A Band Pass mask will appear at the center of the image.
3. Adjust the position of the two band-pass frequencies.

To add a Periodic mask


The Periodic mask adds a mask suitable for filtering periodic images. The array is
formed from two basis vectors with their origins at the center of the Fourier transform.
The ends of these vectors can be moved around by dragging the handles. Also, the
radius and shape of each of the ovals can be changed by dragging the handles of the
oval in the center.
1. If you are viewing the image document in page mode, select the image to which
you want to add a Periodic mask.
2. Click on the image with the Periodic mask tool.
A Periodic mask will appear at the center of the image.
3. Adjust the position of the two vectors.
4. Adjust the size of the mask oval.
You can tell DigitalMicrograph to treat each vector as more than one unit
vector. This can make it easier to position the periodic mask if the unit vectors
are very short.
1. Select the Periodic mask which you want to change.
2. Choose Object Info under the Display menu.
3. Select Periodic Array->Options on the left side of the dialog box.
The Options panel will appear in the right side of the dialog box.
4. Enter the desired number of reciprocal lattice units each vector represents.
5. Click OK.
Each vector in the Periodic mask will represent multiple units now.
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

96

To add a Wedge mask


The Wedge mask puts an annular wedge on the image. The wedge is formed by two
lines going through the origin of the Fourier transform. You can adjust the directions of
these lines by adjusting either of the arrows.
1. If you are viewing the image document in page mode, select the image to which
you want to add an annular Wedge mask.
2. Click on the image with the Wedge mask tool.
A Wedge mask will appear at the center of the image.
3. Adjust the position of the two wedge border directions.

To apply a mask to a Fourier image


After you have prepared the masks on your image, you need to "apply" the mask to
your image.
1. Click on the masked image and select Apply Mask from the Process menu.
A dialog will appear asking for parameters of the mask application.
2. Enter the number of pixels by which to smooth the edge of the mask.
The edges of the mask are smoothed by convolution with a Gaussian function.
The number entered in the dialog box is the half-width of the Gaussian used.
3. Check the Opaque check box as desired.
You can check or un-check the Opaque edit box to give you a choice of
treating the mask on the image either as the part of the data that is saved
(opaque not checked) or the part of the data that is set to zero (opaque
checked).
4. Click OK.
DigitalMicrograph will apply the mask on the complex image and create a new
image.

To create a union of masks


You can prepare two different masks on the same image by first preparing one and
then adding another onto the same image so you will have masked areas that are the
"union" of the two masks.
Copyright 2012 Gatan Inc. All Rights Reserved.

97

DigitalMicrograph

To create an intersection of masks


You can prepare an intersection of two masks on the same image.
1. Add the first mask to the image.
2. Apply the mask to the image.
A new masked image will be created.
3. Add the second mask to the masked image.
4. Apply the mask to the masked image.
A new image will be created that is the intersection of the two masks.

1.5.7

Image Analysis

1.5.7.1

Calculating Image Statistics

Calculating Image Statistics


DigitalMicrograph can calculate certain statistical information about images.
To calculate statistics of an image's pixel values
You can calculate certain statistics of the pixel values in your image.
1. Make sure the Results window is open.
Choose Open Results from the Window menu to open the Results window if it
is not open already.
2. Select the image from which to calculate statistics.
3. Choose the desired statistics from the Statistics submenu under the Analyze
menu.
The results of the calculations will be displayed in the Results window.
1.5.7.2

Using Histograms

Using Histograms
DigitalMicrograph can automatically calculate the histograms of images with Raster or
Surface Plot displays.
A histogram based on the displayed image is shown in the Histogram palette. A more detailed
histogram can be generated and displayed in a line plot image display. The histogram will
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

98

automatically regenerate when its source image changes.

To get a detailed histogram of an image


You can get a detailed histogram of the image in which you are interested.
1. Select the image from which you are interested in calculating a histogram.
If the image has a single rectangular region of interest, the histogram will be
calculated for the area within that rectangle only.
2. Choose Histogram under the Analyze menu.
To select additional options, hold down the Alt key while choosing the menu
item. (Make sure you hold down the Alt key before clicking on the menu bar.)
The Histogram Options dialog will appear.
Enter the desired number of channels to be used in the histogram calculation. The
more channels, the slower the calculation will be.
A new image displayed as a Line Plot and representing the histogram will be
displayed. The Histogram will continue to update whenever the source changes.
1.5.7.3

Particle Analysis

Particle Analysis
DigitalMicrograph provides many features for particle analysis. The basic steps for analyzing
particles are to prepare the source image for particle analysis, threshold the source image,
find the particles, and finally analyze the particles.
1.5.7.3.1 Image Preparation

Image Preparation
Image preparation attempts to distinguish the particles from non-particle portions of the
image (such as the background of the image). This step is the precursor to thresholding the
image.

To prepare an image for thresholding


Typically, you will want to make sure that the particles are easily distinguishable using
a histogram. In order to do this, you may want to attempt to flatten the background of
the image.

To flatten the background with filters


To generate the background image, you can use one of the non-linear filters, such as
Copyright 2012 Gatan Inc. All Rights Reserved.

99

DigitalMicrograph

Minimum or Maximum filters. Then subtract the resulting background from the original
image.
1. If you are viewing the image document in page mode, select the image of which
you want to flatten the background.
2. Apply an appropriate filter to generate a background image.
The Minimum filter can be used when the background is darker than the
particles.
The Maximum filter can be used when the background is lighter than the
particles.
3. Use simple math to subtract the background from the original image.
You will now have an image with the background flattened.
1.5.7.3.2 Thresholding

Thresholding
The process of separating the particles from the rest of the image is called thresholding. In
order for thresholding to be effective, you must start with an image in which the particles are
easily distinguishable in the histogram. Ideally, a histogram of an image containing particles
will contain two major peaks: one for the background, and one for the particles. In practice,
the peaks may not be clearly distinguished.

To threshold an image
You can threshold an image using a histogram.
1. If you are viewing the image document in page mode, select the image you want to
threshold.
2. Choose Start Threshold under the Particles menu.
A line plot with the histogram will appear.
You can stop thresholding by choosing Stop Threshold under the Particles
menu. Do not do this until you are completely done with the particle analysis.
3. Use the Pointer tool to make a selection on the histogram.
The area on the source image corresponding to the selected area on the histogram
will be highlighted in green.
4. Change the selection on the histogram as desired.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

100

The source image mask will change when you change the selection on the histogram.

To use the Magic Wand tool


You can also have DigitalMicrograph automatically threshold an image by using the
Magic Wand tool.
1. If you are viewing the image document in page mode, select the image you want to
threshold.
2. Click on a particle using the Magic Wand tool.
DigitalMicrograph will find particles with similar intensity values to the particle you
clicked on. DigitalMicrograph will normally select a range of intensity values between
the lowest intensity in the image and intensities similar to where you clicked.
You can use the Pointer tool to modify the selection on the histogram.
1.5.7.3.3 Finding Particles

Finding Particles
Once you have a threshold defined for the image, you can have DigitalMicrograph find the
individual particles for you.
Once you find the particles, you can analyze all of them or certain particles individually. Each
particle mask can be selected or deselected. Analysis works on the selected particles. You
can delete, cut, copy, and paste selected particles.
To find particles according to threshold
You can find particles once an image has been thresholded.
1. Threshold the image on which you want to find particles.
See "To threshold an image".
2. Choose Find Particles under the Particles menu.
The individual particles will be shown in red. They will be all selected as well,
which is indicated by the yellow outline.
You can change what particles are selected by clicking on individual particles. Hold
down the Shift key to toggle the particle's selected status. Or use the Pointer tool to
select an area within which all particle will be selected.

Copyright 2012 Gatan Inc. All Rights Reserved.

101

DigitalMicrograph

To remove particles touching the edge


You can remove any particles that touch the edge of the image.
1. Threshold an image of interest.
See "To threshold an image".
2. Choose Remove Edge Particles under the Particles menu.
Particles touching the edge of the image will be removed.

To fill holes in particles


You can fill any holes in particles.
1. Select the particles in which you want to fill holes.
2. Choose Fill Holes under the Particles menu.
Particles with holes will be filled in.

To do morphological operations on particles


You can perform standard morphological operations on particles.
1. Select the particles on which you want to perform a morphological operation.
2. Choose Erode, Dilate, Open, or Close from the Particles menu.
The morphological transformation will be applied to the selected particles.

To do particle outlining
You can outline particles.
1. Select the particles you want to outline.
2. Choose Outline from the Particles menu.
The selected particles will be outlined.

To do particle skeletonization
You can skeletonize particles.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

102

1. Select the particles you want to skeletonize.


2. Choose Skeletonize from the Particles menu.
The selected particles will be skeletonized.

To use a region of interest as a particle


You can create any region of interest and treat it as a particle.
1. Create a region of interest.
You can use the Rectangular region of interest tool, the Line of interest tool,
the Closed Loop region of interest tool, or the Open Loop region of interest
tool.
2. Choose Convert to Particle Mask from the Particles menu.
The region of interest will now appear as a particle.
1.5.7.3.4 Analyzing Particles

Analyzing Particles
Once the particles are defined and found, you can analyze the particles. Analyzing the
particles consists of measuring certain parameters such as area, perimeter, dimensions,
etc. for each particle.

About Particle Measurements


DigitalMicrograph provides automatic measurement of numerous particle attributes.
You can decide what measurements to make via the Configure Particle dialog. The
measurements are placed in a separate image with the spreadsheet image display
type. A number representing the particle is attached and shown on each particle.

To set what measurements to make


You can select which measurements you want to make.
1. Choose Configure under the Particles menu.
A dialog will appear asking you to select which measurements to make.
2. Click the All button to measure all attributes.
3. Click the None button to clear all measurements.

Copyright 2012 Gatan Inc. All Rights Reserved.

103

DigitalMicrograph

4. Click on a measurement once to get a description of the measurement.


5. Click on a measurement twice to turn it on or off.
6. Click OK.

To analyze particles
Once you have found the particles and selected the measurements to make, you can
analyze the particles.
Choose Analyze Particles under the Particles menu.
This may take some time. The progress of the analysis is shown in the Progress
Palette.
When the analysis is complete, each analyzed particle will be labeled with a number
and a spreadsheet with the measurements will appear.

1.6

Images
Images
Manipulating, acquiring, displaying, and storing images is the primary purpose of
DigitalMicrograph. This section gives a quick introduction to the basic concepts associated
with images.
DigitalMicrograph deals primarily with images. Each image is represented by a set of
numbers called pixels. For instance, an image that is 200 pixels wide and 300 pixels tall is
represented by 200 x 300 = 60,000 numbers. These numbers are arranged to match the
dimensions of the image, i.e. into 300 rows of 200 numbers each (an array).
Since images are represented by so many numbers, they take up large amounts of memory.
Each image will take up enough memory to store its numbers plus enough memory to display
the image.
DigitalMicrograph also displays images. Images can be displayed in a number of ways, e.g.
similar to a photograph, in a spreadsheet, etc. Images can also be calibrated so that each
pixel's value and location has a physical meaning.

About Data Types


Each pixel in an image is represented by one or more numbers. This representation is
called the data type. Each data type has specific characteristics such as amount of
memory used, precision, and ability to represent different types of numbers.
DigitalMicrograph supports the following five major data types:

Binary
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

104

Pixels represented by 1s and 0s. Each pixel takes one byte of memory.

Integer
Pixels represented by whole, integer numbers. Numbers can be signed
(positive and negative) or unsigned (positive only). Each pixel can take one,
two, or four bytes of memory.

Real
Pixels represented by real numbers. Each pixel can take four or eight bytes of
memory.

Complex
Pixels represented by two real numbers, the real and imaginary components.
Each real number can be represented by either four or eight bytes of memory.
Thus, each complex pixel can be represented by either eight or sixteen bytes
of memory for each pixel.

RGB
Pixels represented by four unsigned one-byte integers, the red, green, blue,
and alpha channels.

About Memory Usage


The memory used by a particular image is dependent on the size of the image and
the data type of the image. The more bytes per pixel of the image, the more memory
used.
Total memory used by an image is calculated by multiplying the dimensions of the
image by the bytes per pixel of the image. The kilobytes of memory (kB) or megabytes
of memory (MB) are found by dividing the total number of bytes by 1024 for kilobytes
and 1,048,576 for megabytes.
For example, a 700 x 800 real data image will take up 700 x 800 x 4 bytes of memory,
or 2,240,000 bytes of memory. This is equivalent to 2187.5 kB and 2.14 MB of
memory.
In addition, each image will use additional memory when displayed.
The amount of memory used by each image and its display is listed under the
Windows menu. Furthermore, the amount of free memory available for use in images
is listed in the Windows menu under Free Memory.

Copyright 2012 Gatan Inc. All Rights Reserved.

105

DigitalMicrograph

About Display Types


Since an image is just a set of numbers, there are many ways to visualize the image.
Images with certain data types can only be displayed by image display methods
suitable for that data type. Some display methods make use of specific information
about the data they are displaying.
DigitalMicrograph generally splits the data types into those that can ultimately be
represented by a single number, and those that can't. All of the binary, integer, and
real data can be trivially represented by a single number. Complex data can be
converted to a single number if you specify how you want to convert it (by taking the
magnitude or phase, for instance). RGB images, on the other hand, cannot be
represented by a single number.
Images that can be represented by single numbers can be displayed using raster,
surface plot, and line plot displays. Images that have RGB pixels can be displayed
using RGB displays. Spreadsheet displays can display images of any type.
More information on Image Displays can be found elsewhere.

About Complex Data


Some displays will only display images with pixels represented as single numbers.
Complex data, though, has two real number components, the real and imaginary
portion. To display complex data, DigitalMicrograph converts a complex number to a
real number through one of five methods:

Real Component.
Takes the real portion of the complex number.

Imaginary Component.
Takes the imaginary portion of the complex number.

Modulus.
Takes the modulus or magnitude of the complex number.

Log of modulus.
Takes the natural logarithm of the modulus of the complex number.

Phase.
Takes the phase of the complex number.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

106

About RGB Data


The RGB display will only display images represented by RGB pixels. This is known
as direct display of the data. DigitalMicrograph only displays what is known as 24-bit
RGB data, which consists of three 8-bit components (red, green, and blue) and an
additional 8-bit component called the alpha channel. This channel exists to optimize
speed of retrieving data stored in memory for data stored in 4-byte chunks can be
accessed faster than that stored in 3-byte chunks. The alpha channel of each pixel is
currently not used by DigitalMicrograph.

About Calibrations
An image is simply a set of numbers arranged into rows and columns.
DigitalMicrograph allows you to calibrate an image so that the row and column
correspond to a physical distance.
For example, if you have an image that is 200 x 300 pixels, it may represent a physical
sample that is 25 x 37.5 nm. DigitalMicrograph could treat each pixel as if it were 25
nm /200 pixels = 0.125 nm wide. Then, whenever DigitalMicrograph reported
measurements, or positions of pixels, it would report them in nanometers instead of
pixels.
Furthermore, in applications such as Atomic Force Microscopy, the intensity of a
particular pixel can be calibrated to represent a physical value.
For example, if you have an image with intensity values in the range of 200 to 1400,
these values may actually represent the physical height of the sample ranging from 30
nm to 210 nm. DigitalMicrograph could treat each pixel value to represent 30 nm/200
= 0.15 nm per intensity unit. Then, whenever DigitalMicrograph reported the value of a
pixel, it would report it in nanometers instead of a raw number.

About Image Status


DigitalMicrograph provides a convenient way to view the type of an image, the position
of the cursor within an image, and the intensity value under the cursor. All
measurements will be displayed as calibrated numbers if calibrations were
performed.
The Image Status palette tells you which image the cursor is on (Image A in figure
above), the data type (Real 4), the size of the image (256 x 256 pixels), the x and y
positions of the cursor (146,155), and the intensity value at that position (0.931697).
The particular information displayed in this palette will depend on the data type,
calibrations, and display type of the image the cursor is on.

Copyright 2012 Gatan Inc. All Rights Reserved.

107

1.6.1

DigitalMicrograph

Setting Image Information

Setting Image information


DigitalMicrograph keeps track of many pieces of information regarding an image such as
calibrations, image size, keywords, and more. You can view and enter information using the
Image Display Info dialog.
Like the Global Info dialog, the Image Display Info dialog is divided into a list of panels along
the left side and the selected panel on the right side. To switch to a different panel, select a
different panel from the list on the left.

To enter or see information about an image


You can see detailed information about an image.
1. If you are viewing the image document in page mode, select the image you want to
inspect.
2. Choose Image Display... under the Display menu.
The Image Display Info dialog will appear.
3. Select Image::Info on the left side of the dialog box.
The Image Info panel will appear in the right side of the dialog box.
4. Enter the name of the image and any additional image description.
The following information will automatically be displayed:
Data Type
Size in Pixels
Size in Bytes
Dimensions
Pixel Size

The data type of the image.


The size of the image in pixels.
The size of the image in bytes.
The dimensions of the image as calibrated.
The calibrated size of an individual pixel.

5. Click OK.
Switching to a different panel will automatically save your choices.

To change the name of an image


You can change the name of the image document in which the image is contained.
1. If you are viewing the image document in page mode, select the image of which
you want to change the name.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

108

2. Choose Image Display under the Display menu.


The Image Display Info dialog will appear.
3. Select Image::Info on the left side of the dialog box.
4. Enter the name of the image in the name field.
5. Click OK.

To enter a description of an image


You can enter a description of an image that will be stored with the image.
1. Select the image for which you want to enter a description.
2. Choose Image Display under the Display menu.
The Image Display Info dialog will appear.
3. Select Image::Info on the left side of the dialog box.
4. Enter the description of the image in the description field.
The description can be up to 32 kB in length.
5. Click OK.

To edit an image's tags


DigitalMicrograph keeps an internal database of assorted information such as user
preferences, algorithm options, and other data vital to the operation of
DigitalMicrograph. Some of this information is stored with an image. You can directly
edit this information.
Editing tags is a very advanced use of DigitalMicrograph and should, in general, not be
performed unless you have explicit instructions on how to do so. It is possible to make
images unloadable by editing tags.
1. If you are viewing the image document in page mode, select the image for which
you want to edit its tags.
2. Choose Image Display under the Display menu.
The Image Display Info dialog will appear.
3. Select Image::Tags on the left side of the dialog box.

Copyright 2012 Gatan Inc. All Rights Reserved.

109

DigitalMicrograph

The Tags panel will appear in the right side of the dialog box.
4. Enter the information in the right portion of the dialog box.
A list of tags is displayed. You can use the twist-down controls to open up
groups and lists of tags.
Edit
Add
Remove

Click this button to edit the selected tag


Click this button to add a new tag
Click here to remove the selected tag

5. Click OK.

Switching to a different panel will automatically save your choices.

1.7

Reference
Reference

1.7.1

Toolbars

Toolbars
1.7.1.1

File Tools

File Tools
The File Tools toolbar contains the most used commands from the File and Edit menus.
If this toolbar is not open, then double click on the toolbar to get the Customize Toolbar dialog.
Select File Tools and hit Close. If no toolbar exist, select Customize Tools from the Window
menu to open the same dialog.

Explanation
Open, New Script, Save, Save Numbered, Save Display and Print perform the same
action as the matching items in the File menu. Preferences opens the Global Info
dialog.
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

110

Add Databar performs the same action as the Add Databar item in the Edit::Data Bar
sub menu. Delete Databar does not have an equivalent menu item. See Databar for
more info on the databar functionality.
Print Preview puts the image document in Page mode and applies the Databar.
1.7.1.2

Standard Tools

Standard Tools
DigitalMicrograph initially includes a Standard Tools palette with 10 tools. Plug-ins to
DigitalMicrograph can add more tools to this palette so yours may look different.
If this toolbar is not open, then double click on the toolbar to get the Customize Toolbar dialog.
Select Standard Tools and hit Close. If no toolbar exist, select Customize Tools from the
Window menu to open the same dialog.
You can click on a tool to make it the active one. Some tools can only be used once, after
which the palette will reset to the Pointer Tool. If you want to repeatedly use one of those
tools, you can right click on it to make it the default tool.

Pointer Tool
This is the standard tool for selecting and moving objects, such as windows, ROI's
and annotations .

Hand Tool
The Hand tool is used for moving the image display within the window.

Magnifying Glass
The Magnifying Glass is used for zooming in on the image. Hold down the Alt key to
zoom out.

Copyright 2012 Gatan Inc. All Rights Reserved.

111

DigitalMicrograph

Text Annotation Tool


Select the Text Annotation Tool for adding text to your image or image document. For
more information see Annotations.

Line Annotation Tool


Select the Line Annotation Tool for adding lines and arrows to your image or image
document. For more information see Annotations.

Rectangle Annotation Tool


Select the Rectangle Annotation Tool for adding rectangles and squares to your
image or image document. For more information see Annotations.

Oval Annotation Tool


Select the Oval Annotation Tool for adding ovals and circles to your image or image
document. For more information see Annotations.

Magic Wand Tool


Use the Magic Wand Tool for automatically thresholding images. For more
information see Thresholding..

Line Profile Tool


Use the Line Profile Tool to create a Line Profile on the image. For more information
see Using Line Profiles.

X-ray zapper Tool


Use the X-ray zapper Tool to remove point blemishes from images. This tool is most
useful to remove X-ray induced bright spots in images from CCD cameras.
1.7.1.3

Line Plot Tools

Line Plot Tools


The Line Plot tools are used to change the display of a Line Plot Image Display. For detailed
information about its usage, see "Using Line Plot Image Displays".
If this toolbar is not open, then double click on the toolbar to get the Customize Toolbar dialog.
Select LinePlot Tools and hit Close. If no toolbar exist, select Customize Tools from the
Window menu to open the same dialog.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

1.7.1.4

112

ROI Tools

ROI Tools
Regions of Interest (ROI's) are used to select certain parts of an image. For example, the
Rectangle ROI tool can be used to select a section of an image that can then be copied and
pasted elsewhere.
If this toolbar is not open, then double click on the toolbar to get the Customize Toolbar dialog.
Select ROI Tools and hit Close. If no toolbar exist, select Customize Tools from the Window
menu to open the same dialog.
More information about ROI tools can be found in "Using Regions of Interest".

1.7.1.5

Masking Tools

Masking Tools
The Masking Tools are most often used for Fourier Filtering. For detailed information about its
usage, see "Using Fourier Masking".
If this toolbar is not open, then double click on the toolbar to get the Customize Toolbar dialog.
Select Masking Tools and hit Close. If no toolbar exist, select Customize Tools from the
Window menu to open the same dialog.

Copyright 2012 Gatan Inc. All Rights Reserved.

113

1.7.2

DigitalMicrograph

Floating Palettes

Floating Palettes
1.7.2.1

Histogram

Histogram
The Histogram palette displays the histogram of the currently selected image, if the image is
displayed in Raster or Surface Plot mode. It also shows the Color table, and the Contrast
Transform curves used for calculating the index in the Color Table from the image data.

See "About Histograms" for more detailed information.


1.7.2.2

Display Control

Display Control
The Display Control palette is used to change the contrast, brightness and gamma of image
displayed in raster or surface plot mode, and using a linear color transformation.
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

114

See "To Change Brightness/Contrast/Gamma Graphically".


1.7.2.3

Image Status

Image Status
The Image Status palette shows information about the currently selected image at the current
location of the cursor.

The first three lines display which image the data refers to (here Image B), the data type (here
Integer 4 Byte Signed), and the size of the image (here 256 by 256 pixels).
Next are the X and the Y location. These are here displayed in calibrated units with respect to
the origin. And finally the intensity value, also displayed in calibrated units.
The values for X, Y and Value can also be displayed in non-calibrated units by disabling the
calibration.
See "Using Calibrations" for information on how to set the image and intensity calibrations,
Copyright 2012 Gatan Inc. All Rights Reserved.

115

DigitalMicrograph

and how to enable/disable display of calibrations..


1.7.2.4

Target

Target
The Target palette is used to set the view mode, select the target when in Page mode, and to
enable/disable calibrations.

Target selection is useful when applying annotations since annotations are always attached
to a target (see "About Targets").
The Target palette displays a small ruler before each image that is calibrated. Clicking on this
ruler will enable/disable display of the calibrations (see "Using Calibrations").
1.7.2.5

Control

Control
The Control palette is used to view and edit annotation location. See "Annotations".

The Control Palette shown here is used for Rectangle and Oval annotations. It displays X and
Y position, plus Width and Height.
A different version used for Line annotations displays X, Y, Length and Rotation.
A version used for image display annotations is similar to the one displayed here, plus it has
an entry labelled Zm for Zoom.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

1.7.2.6

116

Slice

Slice
The Slice palette is used to select a slice in a three dimensional image.

See "Using the Slice Tool" for more information.


1.7.2.7

Progress

Progress
The Progress Window can contain 3 lines of text to inform the user about the progress of a
lengthy operation. It is also easy to use it from the scripting language through the function:

OpenAndSetProgressWindow( "Line1", "Line2",


"Line3" )

1.7.2.8

Acquisition Status

Acquisition Status
The Acquisition Status window is used by a couple of DigitalMicrograph plug-ins to inform the
user of the status of a long process. This is similar to the usage of the Progress window.

Copyright 2012 Gatan Inc. All Rights Reserved.

117

1.7.3

DigitalMicrograph

Shortcuts

Shortcuts
DigitalMicrograph provides many keyboard shortcuts. Most of those shortcuts are equivalent
to menu items and the shortcut can be read on the menu item. For example in the File menu,
the Open... item has "Ctrl+O" listed on it. This means that pressing the "O" key, while holding
down the Control key will be equivalent to choosing Open... from the File menu.
Some other shortcuts in DigitalMicrograph are not displayed on menu items:

Shift-Ctrl-W
Close all windows, but ask the user whether to save them, if needed.

Alt-Shift-Ctrl-W
Close all windows, including the Results window, and do not ask the user if data
needs to be saved.
If you want to just close all the image windows, you can hold down the Alt, Ctrl and
Shift keys and then click in the close box of one of the image windows. In a similar
way can you close all script windows.

Alt-Ctrl-W
Close the foremost window without asking the user if the related data needs to be
saved.
You can also hold down the Alt key, and then click in the close box of the image
window you want to close.

Alt-Ctrl-F4
Close DigitalMicrograph without asking the user to save any data.

Alt-Ctrl-V
Paste image data in the paste buffer in a new image document window.

Alt-Ctrl-X
Cut the ROI from the image.
With the normal Cut command on the File menu, or with Ctrl-X, you cut the data in the
ROI. When you hold down the Alt key as well, you actually cut the ROI itself, which
you can then paste into another document.

Alt-Ctrl-C
Copy the ROI from the image.
With the normal Copy command on the File menu, or with Ctrl-C, you copy the data in
the ROI. When you hold down the Alt key as well, you actually copy the ROI itself,
which you can then paste into another document.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

118

Alt-Ctrl-H
Show the options dialog for setting the number of channels in the Histogram and then
display the histogram. See "Using Histograms".

Alt-Ctrl-T
Show the options dialog for setting the number of channels in the Histogram and then
display the histogram for Thresholding. See "Thresholding".

1.8

Scripting
Scripting
The DigitalMicrograph script language allows the customization of DigitalMicrograph's image
acquisition and processing capabilities to accommodate user specific applications.
A brief overview of some of the simplest features is given in this chapter.

Getting Started
Scripts are lists of instructions to DigitalMicrograph.
A typical procedure for performing some calculation upon an image is as follows:

1. Open a script window.


You open a script window by choosing New Script from the File menu are by
hitting Ctrl-K. When you do this, a text editing window will appear. It will look
like the window in the figure below.

2. Type in the script which tells DigitalMicrograph what to do.


Copyright 2012 Gatan Inc. All Rights Reserved.

119

DigitalMicrograph

3. Run the script by pressing Ctrl-Enter.


A script window is a document window. You can save, open scripts, and print
scripts, just as you would any other document. If you save scripts, they can
be edited using DigitalMicrograph or any other word processor-type program,
such as Notepad.
When you are processing images using scripts, you will need to refer to the
images in some manner. When you have images in windows, a letter appears
in the title bar of the image to the left of the title (see the figure below). These
letters are called the image letters.

Within a script, you can refer to different images with their letters. Each image
within DigitalMicrograph will have a unique letter.

Simple Image Processing Scripts


Simple scripts are best described by providing a few examples.
Let's say that you want to add two images, "a" and "b", together. You can do this with
the following script:

c = a + b
This script will create a new image "c" which would contain the sum of "a" and "b".
So the whole procedure for using this script is as follows:

1. If DigitalMicrograph is open, quit the program and restart it.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

120

This insures that the two images we are going to create end up labeled "a" and
"b".

2. Choose New under the File menu.


This will create the first image.

3. Again, choose New under the File menu.


This will create the second image.

4. Open a script editor window by choosing New Script under the File
menu.
5. Type in the script "c=a+b" into the window.
6. Press Ctrl-Enter to run the script.
Notice that a new image has been created which is the sum of the other two
images.
You can also store the images back into themselves. For instance, instead of
creating a new image "c", you could just type:

a = a + b
This way, the new image "a" would contain the sum of the old image "a" and
the image "b".
Note: Any images appearing in expressions in this chapter must be the same
size. If the images are of different sizes, the examples in this chapter will not
work.

Using the Selection


You can also operate on any user selection, if there is one. To do this, add a "[]" after
each image from which you want to user the selection. Again, all image sizes
(selection sizes) must be the same in the expression.
For example,

a[] = a[] + b[]


would add the selected area of "a" and "b" and store the result in the selected area of
"a".
If "a" had a selection that was smaller than the entire image, the following,

Copyright 2012 Gatan Inc. All Rights Reserved.

121

DigitalMicrograph

a = a[] + b[]
would be illegal since the area of "a[]" and "a" is different.

Mathematical Functions
The are many predefined mathematical functions available for use in scripts. A partial
list is given below:

b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b
b

=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=
=

a + b
a - b
a * b
a / b
-a
a ** 4
abs(a)
acos(a)
asin(a)
atan(a)
atan2(a,b)
atanh(a)
cos(a)
cosh(a)
exp(a)
exp1(a)
exp2(a)
exp10(a)
log(a)
log1(a)
log2(a)
log10(a)
max(a)
min(a)
mod(a)
rem(a)
round(a)
sin(a)
sinh(a)
sqrt(a)
tan(a)
tanh(a)
trunc(a
!a
a && b
a || b
a != b

// addition
// subtraction
// multiplication
// division
// negation
// power
// absolute value
// arc-cosine
// arc-sine
// arc-tangent
// arc-tangent of a/b
// arc-hyperbolic tangent
// cosine
// hyperbolic cosine
// exponential
// exponential - 1
// 2 raised to the power of a
// 10 raised to the power of a
// logarithm
// logarithm of a + 1
// log base 2
// log base 10
// maximum value of a
// minimum value of a
// modulo
// remainder
// rounded
// sine
// hyperbolic sine
// square root
// tangent
// hyperbolic tangent
// truncated
// logical NOT
// logical AND
// logical OR
// not equals (result 1 or 0)
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

b
b
b
b

=
=
=
=

a == b
a < b
a > b
a <= b
or 0)
b = a >= b
1 or 0)

//
//
//
//

122

equals (result 1 or 0)
less than (result 1 or 0)
greater than (result 1 or 0)
less than or equal (result 1

// greater than or equal (result

All of the functions act upon each pixel of an image in turn. For instance, saying

a = a < b
will assign a value of 1 to every pixel in "a" where that pixel is less than the
corresponding pixel in "b" and a value of 0 to every pixel in "a" where the pixel is not
less than the corresponding pixel in "b".
You can create more complicated expressions by grouping together functions using
parenthesis. For example:

a = (b + c) * sin(d)

Opening Scripts
You can open scripts by choosing the Open item under the File menu. When you do
so, you will be prompted with the standard file opening dialog box.
DigitalMicrograph can open files of many different types such as images and scripts,
see the figure below.

DigitalMicrograph can open any plain text file.


Copyright 2012 Gatan Inc. All Rights Reserved.

123

DigitalMicrograph

Executing Scripts
As mentioned before, the way to run or execute a script is to press Ctrl-Enter with the
desired script's window in front. This is the most important action to remember when
working with scripts in DigitalMicrograph.

Saving Scripts
When you have made changes to a script an you wish to save it to disk, you can just
choose Save under the File menu and the script will be saved to wherever you loaded
it from.
When the script has not been previously saved to disk or when you want to save a
script to a new file by choosing Save As... under the File menu, you will be presented
with a save dialog box (see figure below).

Printing Scripts
To print a script:

1. Click on the desired script's title bar to bring it to the front of the other
windows.
2. Choose Print under the File menu.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

124

You will be presented with a Print dialog box (see figure below). The actual
dialog box you get will depend on the printer you are using and the version of
system software; however, it will look similar to the figure below).

3. Set the printing options you want to use


See the manual that came with your printer for an explanation of the options.

4. Click OK.

Installing and removing a script in a Menu or Library


Scripts can be installed as a library or to be run from a menu item, depending on the
kind of code in the script: if your script just has a collection of functions that you want
to use from other scripts, then you want to install it as a library; if running your script
actually does something, then you can install it as a menu item.

1. Click on the desired script's title bar to bring it to the front of the other
windows.
2. Choose Install Script... under the File menu.
This will produce the following dialog box:

Copyright 2012 Gatan Inc. All Rights Reserved.

125

DigitalMicrograph

Here you can choose whether to install as library or as a menu item, and in the
case of a menu item, you can specify the location in the menu structure.

You can also install scripts directly from a file:


1. Choose Install Script File ... under the File menu.
This will produce a file open dialog where you can select the script you want to
open.

2. Hit the Open button


Now the install script dialog as shown above is displayed, and you can choose
how to install your script.
To remove a script:

1. Choose Remove Script ... under the File menu.


2. Select the script you want to remove, and hit the Remove button

Script Language Conventions


A. The DigitalMicrograph script language is case insensitive.
This means that the following variations of the function Result() are
equivalent.

result( "testing 1 2 3\n" )


Result( "testing 1 2 3\n" )
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

126

RESULT( "testing 1 2 3\n" )


The "\n" in the quotes specifies the newline character.

B. There are two ways of commenting scripts.


The first is the "//" notation. The rest of a line following the "//" is treated as a
comment. For example,

result( "testing 1 2 3\n" ) // some note to


myself
The second notation for commenting is the "/* */" notation. Any text between
the starting "/*" and the ending "*/" is treated as a comment, including
newlines. It can be used like this:

/*
This is a multiline
comment.
*/
The "/*" and "*/" can also be on the same line. For example,

result( "testing 1 2 3\n" ) /* another note to


myself */
C. Statements must be separated by either a newline or ";".
All of the above examples use newlines. An example of using ";" as a
separator is:

number value = 1 + 2; Result( value + "\n" )


D. Script expressions must fit on one line or use the continuation
character.
If a statement or expression doesn't fit on one line you can end one line with a
"\" (called a backslash), which indicates the expression is continued on the
next line. For example,

number value = 1 + 2 + 3 + 4 + 5 \
+ 6 + 7 + 8 + 9 + 10
result( value + "\n" )
Here value will equal 55 because the first statement continues to the second
line. If the backslash were omitted you would get an error when trying to run
this script.
Copyright 2012 Gatan Inc. All Rights Reserved.

127

1.8.1

DigitalMicrograph

Types and Variables

Types and Variables


Variables are used to store values in a script. The type of a variable determines the kinds of
things that can be represented with it. The DigitalMicrograph script language has types for the
representation of numbers, images, and strings.

Types
The basic script language types are:

realnumber
complexnumber
rgbnumber
realimage
compleximage
rgbimage
realsubarea
complexsubarea
rgbsubarea
string
In addition, 'number' is shorthand for 'realnumber', 'image' is shorthand for 'realimage',
'subarea' is shorthand for 'realsubarea'.

Variables
A variable has a name and a type. Variables must be declared before being used, with
the exception of image letters and intrinsic variables. The type of a variable
is specified in its declaration.
Variable names must start with a letter an be made up from the letters a-z, A-Z, the
numbers 0-9, and the underline character ("_"). Examples of valid variable names are
count, B123, r2d2, macStyle, and unix_style.

Variable Declaration
A declaration specifies a type and is followed by a list of one or more variables of that
type. Some examples of simple definition are:
number count
number xyz
complexnumber abc
string title
image img

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

128

An example of defining several variables of the same type is given by:


number lower, upper
complexnumber alpha, beta, gamma
A variable may also be initialized in its declaration. Valid initializing expressions must
use either = or :=. Some examples are:
number lower = 50
number upper = lower + 100
complexnumber alpha = complex( 1, 0 )
string title = "Untitled"
image background := IntegerImage( "Background", 2, \
1, 256, 256 )

Image Variables
Image variables are said to refer to images. More than one image variable can refer to
the same image. An image will be deleted when it is no longer referenced by any
image variable unless it is displayed or KeepImage() has been called for it.

Image Letters
Image letters are predefined variables which can be used as shorthand to reference
images.
The image letters for any particular image are the letters followed by a colon in the title
of an image window. The possibilities are a to z and aa, ab, ... to zz. If a variable
name is used that has not been declared first and it is a valid image letter, the script
language will assume that it refers to the corresponding image.
Throughout this text the convention is used that when a statement is made that image
variable xyz is set to the result of some operation, what is normally meant is that the
image referred to by xyz has been set the result of the operation.
For example, given three images of the same size and data type that correspond to
the image letters a, b, and c respectively,
a=b+c
This single line script will add each pixel of b to c and store the result in a.
If a variable is declared with a name that is an image letter, the declaration overrides
the use of that name as an image letter within that script. Any usage of the over-ridden
name will refer to the declared variable and not to the predefined image letter. For
example,
number a = 2
number b = 3
Copyright 2012 Gatan Inc. All Rights Reserved.

129

DigitalMicrograph

number c = a + b
result( c + "\n" )
This is perfectly legal even if there are images in existence that correspond to the
image letters a, b, and c.

Intrinsic Variables
Intrinsic variables are predefined variables that have context dependent values.
Following is a list of all intrinsic variables:
icol
icolumn
iheight
ipoints
iradius
irow
itheta
iwidth
iplane
All of these variables pertain specifically to image expressions which will be covered
in the section Pixel By Pixel Operations in the Image Operations chapter.

1.8.2

Expressions

Expressions
An expression may be a constant, variable, function call, or be composed of one or more
operations. Operations are represented by operators. For example, "==" is the equality
operator. The parameters of the operation are the operands.
Operators that work on one operand are called unary operators. Operators that work on two
operands are called binary operators.
An expression composed of two or more operations is called a compound expression. The
order of evaluation is determined by precedence and associativity. Order of evaluation will be
covered later after operators are discussed.

Constants
The simplest kind of expression is a constant. A constant is a value that can't be
changed. There are three different types of constants: Number, Character, and String.
Number Constants
Some examples of number constants are:

-2.34

.456

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

130

It should also be noted that "scientific" notation is also allowed.

5.78383e-7

-2e10

.34E+5

The type of the above number constant examples is realnumber.


Character Constants
A character constant is one character between single quotes. For example,

'?'

'a'

'2'

' ' (blank)

A single quote character constant is specified by '\''. A new line character constant is
specified by '\n'. A character constant's type is realnumber.
String Constants
A string constant is zero or more characters surrounded by double quotes, as in:

"" // (empty string)

"1"

"a string constant."

A double quote may be imbedded in a string constant by "\"". As an example:

"\"scientific\" notation is allowed"


In this example the word scientific would be printed with quotes around it. A newline
may be imbedded in a string constant by "\n". An example is:

"This will be followed by a newline.\n"


A string constant's type is string.

Arithmetic Operators
The arithmetic operators are:
Operator
+
*
/
**
-

Meaning
Addition
Subtraction
Multiplication
Division
Exponentiation
Negation

Use
expr + expr
expr - expr
expr * expr
expr / expr
expr ** expr
- expr

The predefined arithmetic operators are defined for real, complex, and RGB number
expressions; with the one exception: the operator ** is not defined for RGB number
expressions. In addition the + operator is defined for string expressions.
Copyright 2012 Gatan Inc. All Rights Reserved.

131

DigitalMicrograph

Equality, Relational and Logical Operators


The equality, relational, and logical operators evaluate to 1 (true) or 0 (false) and have
the return type of realnumber.
The equality operators are:
Operator
==
!=

Meaning
Equality
Inequality

Use
expr == expr
expr != expr

The equality operators are defined for real, complex, and RGB number expressions
as well as string expressions.
The relational operators are:
Operator
<
<=
>
>=

Meaning
Less Than
Less Than or Equal
Greater Than
Greater Than or Equal

Use
expr < expr
expr <= expr
expr > expr
expr >= expr

The relational operators are only defined for real number expressions.
The logical operators are:
Operator
!
||
&&

Meaning
Logical NOT
Logical OR
Logical AND

Use
! expr
expr || expr
expr && expr

The logical operators are only defined for real number expressions.

Assignment Operators
The assignment operators are:
Operator
=
:=
+=
-=
*=
/=

Meaning
Assign by Value
Assign by Reference
(see text)
(see text)
(see text)
(see text)

Use
expr = expr
expr := expr
expr += expr
expr -= expr
expr *= expr
expr /= expr

The operator = is used for assignment by value. This is the operator that is used to
change the value of a number or string variable. For example, given the number
variable value and the string variable str as already defined variables,

value = 2
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

132

str = "xyz"
When the = operator is used with image variables it will change the value of the pixels
in the image that the variable references. For example, given image a,

a = 0
This sets all pixels in the image a to 0.
Use the := operator to change the image an image variable references. For example:

image frontImage := GetFrontImage()


frontImage = -frontImage
This changes the image variable frontImage to refer to the current frontmost image. It
then negates the image referred to by frontImage.
If the = operator had been used a very different result would have been produced. For
example,

image frontImage = GetFrontImage()


frontImage = -frontImage
This causes the implicit creation of an image of the same size as the frontmost
image. The image variable frontImage is then changed to refer to the implicitly
created image. The frontmost image is then assigned by value to the image referred
to by frontImage. Then the image referred to by frontImage (which is different than the
frontmost image) is then negated. When the script is finished executing and the
image referred to by frontImage has not been shown (and therefore no longer needed)
it is deleted automatically. The frontmost image would not be affected. (This situation
is a common mistake for a novice script programmer to make.)
An image variable may reference several different images during the course of
execution. Given the real images a and b,
...
image tmp
tmp := a
tmp = 2
tmp := b
tmp = 3
...
This script fragment will set all of the pixels in the image that a references to 2 and all
of the pixels in the image that b references to 3.
The operators +=, -=, *=, and /= are shorthand for the combination of = and +, and so
on. In effect,

Expr1 = Expr1 + Expr2


is equivalent to:
Copyright 2012 Gatan Inc. All Rights Reserved.

133

DigitalMicrograph

Expr1 += Expr2
Increment and Decrement Operators
The increment and decrement operators are
Operator
++
--

Meaning
Increment
Decrement

Use
expr ++ ++ expr
expr -- -- expr

The operator ++ adds 1 to its operand and the operator -- subtracts 1 from its
operand. For example, you could write:
number i
for ( i = 0; i < 5; i = i + 1 )
result( i + "\n" )
or equivalently you could write:
number i
for ( i = 0; i < 5; i++ )
result( i + "\n" )

The Arithmetic if Operator


The arithmetic if has the form
expr1 ? expr2 : expr3
Where expr1 is always evaluated. If expr1 evaluates to true (not 0) expr2 is evaluated
and its result used as the value of the whole expression. Otherwise expr3 is evaluated
and its result used as the value of the whole expression. The condition, expr1 must be
a real number expression. The result expressions, expr2 and expr3, may be real,
complex, or RGB number expressions. The type of the arithmetic if expression is
determined by expr2 and expr3.
An simple example is:
number threshold = 100
number value1 = (10 < threshold) ? 42 : 69
number value2 = (110 < threshold) ? 7 : 11
result( value1 + "\n" )
result( value2 + "\n" )
It produces the output:
42
11

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

134

Precedence
The order of evaluation in a compound expression is called precedence. The order in
which the operations in an expressions are evaluated can greatly change it's value.
Parenthesis can be used to change the order of evaluation. A sub-expression
enclosed in parenthesis will be evaluated first before it's value is used.
For example,
4+3*5
(4+3)*5
-4+3
-(4+3)

gives 19
gives 35
gives -1
gives -7

Associativity determines which side of the operator will be evaluated first. For
example, whereas + and * associate left to right (or have left associativity), the
exponentiation operator ( "**" ) has right associativity. Specifically:
3**2**3
gives 6561
(3**2)**3 gives 729
The precedence and associativity of all operators is summarized in the following
table. The table is organized in order of highest precedence to lowest precedence.
Operators on the same line have the same precedence.
Operator
[
!
**
*
/
+
<
>
!=
==
&&
||
?
=
:=
=

++

--

<=

>=

+=

-=

*=

Associativity
left
right
right
left
left
left
left
left
left
/ right

Type Conversion
To understand type conversion we will use an example.
There are three predefined functions for the operator / (divide). One that takes two
real numbers, one that takes two complex numbers, and one that takes two RGB
numbers. Given:
number abc = 4
number def = 2
Copyright 2012 Gatan Inc. All Rights Reserved.

135

DigitalMicrograph

number ghi = abc / def


result( ghi + "\n" )
The value of the variable ghi will be the result of the function for the / operator that
takes two real numbers. Given:
complexnumber abc = complex( 4, -1 )
complexnumber def = complex( 0, 2 )
complexnumber ghi = abc / def
result( ghi + "\n" )
The value of the variable ghi will be the result of the function for the / operator that
takes two complex numbers. Now, given:
complexnumber abc = complex( 4, -1 )
number def = 2
complexnumber ghi = abc / def
result( ghi + "\n" )
Intuitively one might guess that, given the three choices of functions, the function that
takes two complex numbers would be used. The implied conversion of def from a real
number to a complex number is called a type conversion.
There are a number of automatic type conversions that may be applied in order for the
script language to resolve a function call. Here are a few:
RealNumberExpr -> ComplexNumberExpr
RealNumberExpr -> RGBNumberExpr
RealNumberExpr -> RealImageExpr
ComplexNumberExpr -> ComplexImageExpr
RGBNumberExpr -> RGBImageExpr
RealImageExpr -> ComplexImageExpr
There are some standard functions that aid in explicit type conversion. Two are
complex() and rgb(), which are covered in the Script Function Reference.

Inline Images
An inline image is a way of specifying an image of a constant size with defined values
for every element inline. For example,
image a := [3,2]:
{
{ 1, 0, 1 },
{ 0, 1, 1 }
}
MatrixPrint(a)

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

136

This creates a 3 x 2 floating point image. The dimensions ( "[3,2]" ) are specified as
width, height and must be constant positive integers. An example which multiplies two
matrices is:
image a := [3,2] : {{3,4,2},{2,3,-1}}
image b := [3,3] : {{1,-2,-4},{0,-1,2},{6,-3,9}}
image c := MatrixMultiply(a,b)
MatrixPrint(c)
Inline images don't need to be assigned to variables. The following example is
equivalent to the previous example.
MatrixPrint( \
MatrixMultiply( \
[3,2]:{{3,4,2},{2,3,-1}}, \
[3,3]:{{1,-2,-4},{0,-1,2},{6,-3,9}} \
)\
)
The values of the elements can be the result of number expressions, as in:
number theta = pi()/4
image a := [2,2]:
{
{ cos(theta), -sin(theta) },
{ sin(theta), cos(theta) }
}
MatrixPrint(a)
Complex and RGB images can be specified inline also. The type of the elements
determines the type of the inline image. If one of the elements is complex, then the
whole inline image is complex. As an example,
compleximage a := [2,3]:
{
{ complex(2,3), complex(-1,1) },
{ 1, -1 },
{ complex(0,3.8), 0 }
}
MatrixPrint(a)

1.8.3

Statements

Statements
Statements are the fundamental unit of execution in a script. The default order of evaluation of
Copyright 2012 Gatan Inc. All Rights Reserved.

137

DigitalMicrograph

statements within a script is sequential. However, if all you could write where lists of
instructions that where passed through once you wouldn't be able to do much. Control flow
statements like if, while, and for allow you to change the order of execution.
This chapter covers expressions as statements, the block statement, and all of the control
flow statements in the script language.

Expressions as Statements
Expressions are one kind of statement. For example, the expression:

x = 0
is also a statement.

The Block Statement


The braces { and } can be used to group several statements and variable declarations
into a compound statement or block. A block is syntactically equivalent to a single
statement. The default order of evaluation for statements in a block is sequential.
Variables declared within a block are said to be local to that block. They are not global
to every statement in a script, that is, they are not globally accessible. Whether a
variable is local or global is called its scope. Local variables defined in a block are
created at the start of that block and cease to exist at the end of that block.
Declarations may be intermixed with statements in a block. This allows a style where
a variable is not declared until it is needed.

The if Statement
The if statement is used to make decisions in a program. It has the form:

if ( Expression )
Statement
The Expression is evaluated; if it is "true" (not equal to 0), Statement is evaluated.

The if-else Statement


Like the if statement, the if-else statement is used to make decisions. It has the form:

if ( Expression )
Statement1
else
Statement2

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

138

The Expression is evaluated; if it is "true" (not equal to 0), Statement1 is evaluated;


otherwise (else) Statement2 is evaluated.

The while Statement


The while statement is used create loops in a program. It has the form:

while ( Expression )
Statement
The Expression is evaluated; if it is true Statement is evaluated. Then Expression is
re-evaluated and the cycle is repeated. This continues until Expression evaluates to
0.
An example which counts from one to ten and prints the results using a while loop is
given by:

number count = 1
while (count<=10)
{
Result( count + "\n" )
count++
}
The function Result() takes its argument and prints it in the results window.
Note: If you ever get stuck in an infinite loop, hold down the Control and Break keys to
exit a script at any time

The for Statement


The for statement has the form

for (Statement1; Expression; Statement2 )


Statement3
It is equivalent to:

Statement1
while ( Expression )
{
Statement3
Statement2
}
Semicolons (';') must be used to separate Statement1, Expression, and Statement2
from each other. An example which counts from one to ten and prints the results
using a for loop is given by:
Copyright 2012 Gatan Inc. All Rights Reserved.

139

DigitalMicrograph

number count
for (count=1; count<=10; count++)
Result( count + "\n" )
Note: The for statement should not be used for looping over image pixels, instead an
image expression should be used. The for statement is interpreted and is prohibitively
slow for reasonably sized images, while image expressions are compiled and
execute at close to optimal (for the microprocessor instruction set) speeds. This is
covered in the section Pixel by Pixel Operations contained in the chapter Image
Operations.

The foreach Statement


The foreach statement is used with ObjectLists. For more information on ObjectLists
see ObjectLists. The foreach statement has the form

foreach (Receiver; ObjectList)


Statement
It is equivalent to:

for (index=0; index<ObjectList.SizeOfList(); +


+index)
{
Receiver = ObjectList.ObjectAt(index)
{
Statement
}
}
The break Statement
A break statement exits the smallest enclosing while or for loop. (It also can be used
in conjunction with the try statement which will be covered later.)
A example of using the break statement is given by:

number low = 0
number high = 1
while ( 1 )
{
if ( !GetNumber( "Low Number", low, low )
)
exit( 0 )
if ( !GetNumber( "High Number", high,
high ) )
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

140

exit( 0 )
if ( low <= high )
break
OkDialog( "Your low was greater than your
high!" )
}
Result( "Low: "+low+"\n" )
Result( "High: "+high+"\n" )
When the low number is less than or equal to the high number the loop is terminated
by the break statement. GetNumber() is a predefined function available for your use.
(The exit() function is invoked if GetNumber() returns 0, which indicates the user
pressed the cancel button.)

The continue Statement


The continue statement terminates the current iteration of the smallest enclosing loop
and continues with the next iteration. As an example:

number n = 1
while ( 1 )
{
if ( !GetNumber( "Enter a number from 1
to 10", n, n ) )
exit( 0 )
if ( n < 1 || n > 10 )
{
OkDialog( "Out of range" )
continue
}
result( n + "\n" )
}
This script gets a number from the user and if it is in the range of 1 to 10 prints it in
the results window. If it is "Out of range" it puts up a OkDialog telling the user so, and
then skips printing the result by using a continue statement.

Exceptions - Advanced Topic


Exceptions are a method of handling errors, or exceptional events. DigitalMicrograph uses
exceptions extensively. For example, if the creation of an image fails due to a lack of memory
Copyright 2012 Gatan Inc. All Rights Reserved.

141

DigitalMicrograph

an exception is thrown. Exceptions go outside of the normal flow of control. The only way to
regain control is by use of an exception handling statement, either try-catch or try-recover.
Once an exception is thrown normal evaluation is interrupted. DigitalMicrograph then traces
its steps back through the chain of exception handlers from the point at which the error
occurred until it reaches the top exception handler, which puts up an error dialog.

Throwing Exceptions
An exception may be thrown by use of the Throw() function. For example,

number value
image img := GetFrontImage()
if ( !GetNumberNote( img, "dose", value ) )
Throw( "Missing dose note." )
If the front image does not have a number note with the label "dose" this will throw an
exception with the message "Missing dose note." which will be displayed in an error
dialog.

The try-catch Statement


The try-catch statement is used to handle exceptions. It has the form:

try
Statement1
catch
Statement2
First Statement1 is evaluated. If an exception occurs within Statement1,
Statement2 will be evaluated, after which control will pass to the next higher
exception handling block (any following statements after the t r y -cat ch block
will not be evaluated). If no exception occurs in Statement1, then Statement2 is
ignored.

To avoid re-throwing of the exception place a break statement in the catch block as
follows:

try
Statement1
catch
{
Statement2
break
}
Statement3
Now if an exception is thrown by Statement1, Statement2 gets executed and then
program flow continues after the catch block with execution of Statement3.
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

142

The try-recover Statement


Like the try-catch statement, the try-recover statement is used to handle exceptions.
It has the form:

try
Statement1
recover
Statement2
First Statement1 is evaluated. If an exception occurs within Statement1, Statement2
will be evaluated, after which control will pass to the next higher exception handling
block (any following statements after the try-catch block will not be evaluated). If no
exception occurs in Statement1, then Statement2 is evaluated and control passes to
the next statement. In any case Statement2 is evaluated.

The tryguard Statement


The tryguard statement can be used to trap an exception and post an error message
directly if an exception occurs. It can be used in destructors where exceptions cannot
be thrown.

tryguard( Statement )
Statement is evaluated and if an exception occurs a dialog is posted and exception is
lowered.

1.8.4

Functions

Functions
A function is a user defined operation. A function has a name, an argument list, a return type,
and a body.
The list of operands for a function is called the argument list; an individual operand, an
argument . The argument list determines how many and what type of parameters a function
requires. The argument list is enclosed in parenthesis and the arguments are separated by
commas. If a function has no arguments then the keyword void is used between the
parenthesis.
The type of the result of a function is its return type. If a function does not return any value its
return type is void. The result of a function, if any, is returned by using the return statement.
The body of a function is a statement, which usually is a block statement.
An example of a function declaration is:

number add( number a, number b )


{
Copyright 2012 Gatan Inc. All Rights Reserved.

143

DigitalMicrograph

return a + b
}
For a function to be used it must be called. Most calls have the syntax of the function's name
followed by the actual arguments inside parenthesis. For example,

result( add( 1, 2 ) + "\n" )


When a function is called control passes to the function body, which is evaluated. If a
function returns a value, that value is effectively substituted for that function in the calling
location. Control returns to the caller after evaluation is complete.

Returning a Value
The way a function returns its result is by using a return statement. It has two forms:

return Expression
or

return
The r et ur n statement halts execution at the point at which it occurs in a
function and resumes execution where the function was called.
The type of Expr essi on must be compatible with the type specified as the
function's return type. If the function has a void return type, the return
statement is optional and must not be followed by Expr essi on . Otherwise,
if the function does return a value, the r et ur n Expr essi on form is
required.
An example of the return statement follows:

number AreaOfACircle( number radius )


{
return pi() * radius * radius
}
result( AreaOfACircle( 2 ) + "\n" )

The Function Argument List


A function can have 0 or more arguments. Each argument in the argument list
includes both the name the argument is to be given within the body of the function and
the type that the function expect for that argument. If a function has 0 arguments then
the keyword void is used in place of argument list. For example,

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

144

void PrintDateAndTime( void )


{
result( DateStamp() + "\n" )
}
The arguments of a function are defined only while in that function. They are local to
that function.

Argument Passing
Function arguments may be passed by value or by reference. For example,

void myfunc( number x )


{
result( "x is " + x + "\n" )
x = 2
result( "x is " + x + "\n" )
}
number a = 1
myfunc( a )
result( "After calling myfunc() a is " + a +
"\n" )
Produces the output:

x is 1
x is 2
After calling myfunc() a is 1
As you can see, calling myfunc() in the above example does not modify a. The
argument x was passed by value and did not refer to the original variable. To pass by
reference an "&" character is placed before the variable name in the parameter list in
the function definition. Using the above example again with the single addition of the
"&",

void myfunc( number &x )


{
result( "x is " + x + "\n" )
x = 2
result( "x is " + x + "\n" )
}
number a = 1
myfunc( a )

Copyright 2012 Gatan Inc. All Rights Reserved.

145

DigitalMicrograph

result( "After calling myfunc() a is " + a +


"\n" )
Produces the output:

x is 1
x is 2
After calling myfunc() a is 2
The variable a was modified by the call to myfunc(). This is because x referred to a.

Overloading Functions
An overloaded function is really two or more distinct functions with the same name but
different argument lists. The argument lists must differ either in number of arguments
or in type. For example,

number Add( number a, number b )


{
return a + b
}
number Add( number a, number b, number c )
{
return a + b + c
}
complexnumber Add( complexnumber a, complexnumber
b )
{
return a + b
}
result( Add( 1, 2 ) + "\n" )
result( Add( 1, 2, 3 ) + "\n" )
result( Add( complex( 1, 4 ), complex( 5, -1 ) ) +
"\n" )
which produces the output:

3
6
6 + 3 i
Operators are functions and may also be overloaded. For example, the + operator is
overloaded to work with real numbers, complex numbers, RGB numbers, and strings.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

1.8.5

146

Objects

Objects
In addition to the simple types described in the previous chapter, DigitalMicrograph also
supports objects. In DigitalMicrograph scripting you can create your own objects and you can
use objects already defined within DM. The pre-defined objects include items such as image
windows, image documents, images, image displays, tag groups, and regions of interest.
In this section we will first explain how to define and create your own objects. In later sections
all the pre-defined objects will be discussed.

Define an Object
To define an object you have to declare a class. Here is an example of a shape class.

class shape : object


{
string name
object init( object self, string myname )
{
name = myname
return self
}
number getArea( object self )
{
return 0
}
void print( object self )
{
result( name + ", area = " + self.getArea() +
"\n" )
}
}
The shape class has one member variables: name, and three member methods: init
(), print() and getArea(). Note that each method must have 'object self' as the first
argument. Also note that when referring to an other method of the class from within
the class, such as where the print() method uses the getArea() method, you have to
use the self.methodName() construct. The init() method is generally used as an
initializer to set member variables of the class.
When allocating an object such as shape you call the alloc() function, which takes
one argument: the class name you want to create, followed by the init() function of the
shape class so that you can initialized the member variables. All objects are stored in

Copyright 2012 Gatan Inc. All Rights Reserved.

147

DigitalMicrograph

variables of type 'object'. So to create an instantiation of the shape class, with name
set to "shape", and then execute its print function you would run the following script:

object shape = alloc(shape).init("shape")


shape.print()
Note that the script needs to contain both the class definition of shape and the two
lines above. If you first run a script with the class definition and then the above script,
then DigitalMicrograph will have forgotten what the class definition was and will give
an error.
NOTE: If you run a script from a script window, and that script declares a class, that
class will only be usable during execution of that script. In general, if you want to be
able to use the class outside of your script, you should install the classes as libraries
as explained in "Installing a script library".
The class will be unloaded when the script completes, so no further objects of that
class may be allocated using the class name, but methods dispatched off previously
created objects of that class will continue to work. The class remains available in this
manner as long as any object created from that class exists, or until the class is
explicitly unloaded ( which currently only occurs if the class was installed as a library,
and the library is unloaded ).

ScriptObject class
In the above example the shape class was derived from the ScriptObject class. (Even
if the class wasn't explicitly declared as being derived from object , it still would have
been.) The ScriptObject class is defined as follows

class ScriptObject {
string ClassName( ScriptObject self )
// return name of the object's class
string ParentClassName( ScriptObject self )
// return name of the object's parents class
ScriptObject ScriptObjectClone( ScriptObject self )
// returns a copy/clone of itself
void ScriptObjectCopyFrom( ScriptObject self, object
sourceObject )
// makes itself a copy of the sourceObject
bool ScriptObjectEquals( ScriptObject self, object
compObject )
// returns true if self equals the compObject
bool ScriptObjectIsSameAs( ScriptObject self, object
compObject )
// return true if self is the same object as
compObject

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

148

Number ScriptObjectGetID( ScriptObject self )


// Returns a unique ID for this object. The
object can be recovered by using
GetScriptObjectFromID function.
Number ScriptObjectGetClassToken( ScriptObject
scriptObject, String class_name )
// Gets the token in 'scriptObject'
corresponding to the class 'class_name'.
Boolean ScriptObjectIsValid( ScriptObject
scriptObject )
// Returns true if 'scriptObject' references a
valid object.
Function ScriptObjectLookupMethod( ScriptObject
scriptObject, Function meth_abs, String
class_name )
// Returns the method of this object
corresponding to the abstract method 'meth_abs'
and class 'class_name'.
Function ScriptObjectLookupMethod( ScriptObject
scriptObject, Function meth_abs )
// Returns the specific method of this object
corresponding to the abstract method
'meth_abs'.
}

So one could add to the previous example the following code which would print out the
name of the shape class and the name of its parent class, i.e. object.

result( shape.ClassName( ) + "\n" )


result( shape.ParentClassName( ) + "\n" )
Copying and cloning
The methods ScriptObjectClone() and ScriptObjectCopyFrom() create copies of the
objects. The default implementation for script classes is to do a shallow copy of the
fields ( so if a field references an object, the copied field will reference the same
object ). A class can overwrite this behavior by implementing a method with the
following signature

void CopyFrom( Object self, Object srcObject )


So, for example, we can add a CopyFrom() method to our shape class that provides

Copyright 2012 Gatan Inc. All Rights Reserved.

149

DigitalMicrograph

a custom implementation as in

class shape : object


{
string name
object init( object self, string myname )
{
name = myname
return self
}
string getName( object self )
{
return name
}
void CopyFrom( Object self, Object srcObject )
{
name = "Copy of " + srcObject.getName()
}
number getArea( object self )
{
return 0
}
void print( object self )
{
result( name + ", area = " + self.getArea() +
"\n" )
}
}
object shape1 = alloc( shape ).init("shape")
shape1.print()
object shape2 = shape1.ScriptObjectClone()
shape2.print()
Comparison
The methods ScriptObjectIsSameAs() returns true only if the two objects reference
the same object as in:

object shape1 = alloc( shape ).init( "shape1" )


object shape2 = shape1

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

150

number objectsAreTheSame = shape1.


ScriptObjectIsSameAs( shape2 )
In the default implementation of ScriptObjectEquals(), this function behaves the same
as ScriptObjectIsSameAs(). However, each class can change the behavior of this
function by implementing a method with the following signature

number Equals( object self, object compObject )


So, for example, we can add an Equals() method to the shape class object that
returns true if the names of the shapes are the same, as in the following example

class shape : object


{
string name
object init( object self, string myname )
{
name = myname
return self
}
string getName( object self )
{
return name
}
number Equals( object self, object compObject )
{
return ( name == compObject.getName() )
}
number getArea( object self )
{
return 0
}
void print( object self )
{
result( name + ", area = " + self.getArea() +
"\n" )
}
}
object shape1 = alloc( shape ).init("shape")
object shape2 = alloc( shape ).init("shape")

Copyright 2012 Gatan Inc. All Rights Reserved.

151

DigitalMicrograph

Result( "shape1 and shape2 are the same? " + shape1.


ScriptObjectIsSameAs( shape2 ) +"\n") // no
Result( "shape1 and shape2 are equal? " + shape1.
ScriptObjectEquals( shape2 ) +"\n")
// yes
Inheritance
In the scripting language all methods of a class are virtual and therefore may be
overwritten by derived classes (except for methods of the base ScriptObject class).
All method also must be implemented, so there are no abstract classes in the
DigitalMicrograph scripting language.
To define a new class rect, that extends the shape class you can write the following
code:

class rect : shape


{
number w, h
object init( object self, number width, number
height )
{
super.init( "rectangle" ) // this calls the
init() function of the shape class
w = width
h = height
return self
}
void print( object self )
{
self.super.print() // this calls the print()
function of the shape class
result( "width=" + w + "\n" )
result( "height=" + h + "\n" )
}
number GetArea( object self )
{
return w * h
}
}
Note the use of 'super' to invoke the parent classes method of the same prototype.
To create an instantiation of the rect class, with the width and height set, and then
execute its print function you would run the following script:

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

152

object rect = alloc(rect).init( 5, 7 )


rect.print()
In addition to using 'super' within a class to access the parent class, you can also
accomplish the same thing when using a class, such as in the following example:

object rect = alloc(rect).init(4,3)


rect.print()
// prints rectangle
info
rect.super(shape).print()
// prints shape info
Constructors and Destructors
Classes can have constructors and destructors. Constructors and destructors are
specified by methods with no return type ( not even void ), and only a single argument:
self. The constructor's name is the class name, and the destructor's name is the
class name prepended with a '~'. When an object is created, the constructors of all of
its ancestor classes are called, from least derived to most derived, and when it is
destroyed, the destructors are called in reverse order. If a constructor throws an
exception, destructors are called for each fully contstructed ancestor class, and the
exception is propagated out of the allocation statement. Destructors are not allowed to
throw an exception ( Note that an exception may be thrown from a statement within
the destructor if it is caught and handled in the destructor ).
You could rewrite the original shape class using a constructor as follows

class shape : object


{
string name
shape( object self )
{
name = "uninitialized"
}
void setName( object self, string myname )
{
name = myname
}
number getArea( object self )
{
return 0
}
void print( object self )
{

Copyright 2012 Gatan Inc. All Rights Reserved.

153

DigitalMicrograph

result( name + ", area = " + self.getArea() +


"\n" )
}
}
object shape = alloc(shape)
shape.setName("shape")
shape.print()
Interfaces
DigitalMicrograph support items called interfaces. Once an interface is declared, you
may use the methods defined in the interface on any object. It is up to the
programmer to make sure that the object used actually implements the methods
declared in the interface. If the object doesn't implement a particular method and that
method is invoked, an exception will occur. So interfaces are basically forward
declarations of all functions in the interface. The name of the interface is never used.
Interfaces have nearly the same structure as classes except that you cannot declare
fields or define methods in an interface. Each method in the interface must adhere to
the rules for methods in classes (object as the first argument, etc.) and must be
followed by a semi-colon instead of the body of the function. Furthermore, interfaces
cannot derive from other classes.

interface shapeprinter{
void print( object self );
void printtwice( object self );
}
obj.printtwice()
Weak References
All objects in DigitalMicrograph are reference counted. This means that script
programmers do not need to worry about destructing and/or releasing memory
occupied by any of the objects available in the script language.
Sometime, however, you will need to set up circular references of objects. For
instance, a list may contain an object and that object may contain a reference to the
list. Due to the manner in which reference counting works, this will lead to a situation
where neither object is completely deleted when all references to it are released. This
is because the objects themselves will still contain references to one another.
One solution to this problem is to explicitly release one of the references by setting the
field to a NULL object at some point. This is difficult, however, because the script
language does not support any form of destructor currently.
Another solution involves "weak references." Weak references work the same as
containing the object except that the object may be set to NULL if all other references
to it are released.
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

154

To use weak references, you store the "reference" to the target object in a number.
You can use that number to retrieve the actual object.
For instance, if you have an object called obj, you can use the following code:

number weakRef = obj.ScriptObjectGetID()


The weakRef can be stored in any object. Its storage will not prevent the script object
from being released somewhere else.
To retrieve the object, use the following code:

object obj = GetScriptObjectFromID( weakRef )


Then you need to detect whether the object has actually been retrieved properly:

if ( obj.ScriptObjectIsValid() ){
// do something with object here
}
Resources
Object Lists
DigitalMicrograph includes a class for managing lists of other objects. Currently the
objects contained can only be ScriptObjects (not Image, ImageDocument, etc.). But
you can always place an Image or other class into a simple object and then place the
simple object in the list.

class ObjectList : object


{
long AddObjectToList( ScriptObject, ScriptObject
element )
// add element to the end of the list, returns
the index of the new element.
void ClearList( ScriptObject )
// clears all elements from the list.
void CopyFrom( ScriptObject, ScriptObject from_list )
// replaces the list with the list specified by
the parameter from_list.
bool Equals( ScriptObject, ScriptObject other_list )
// returns true if the other list contains the
same objects as this list.

Copyright 2012 Gatan Inc. All Rights Reserved.

155

DigitalMicrograph

long IndexOfObjectInList( ScriptObject, ScriptObject


element )
// determines whether the element is contained
in the list and returns its index if it is
found.
// Returns -1 otherwise.
long ( ScriptObject, long index, ScriptObject element
)
// inserts element before the given index.
// Index can be 0 to insert at the beginning of
the list.
// Index can be 9E9 to add to the end. It
returns the index of the new element.
long ListContainsObject( ScriptObject, ScriptObject
element )
// determines whether the element is contained
in the list.
void MergeFrom( ScriptObject, ScriptObject
with_list )
// copies any object in with_list that isn't
already in this list to this list.
ScriptObject ObjectAt( ScriptObject, long index )
// returns the element at the given index.
// If the index is out of range, it returns
NULL.
ScriptObject RemoveObjectFromList( ScriptObject,
ScriptObject element )
// remove element from the list. The old element
is returned.
// All elements following the removed element
are moved forward in the list.
ScriptObject RemoveObjectFromList( ScriptObject, long
index )
// remove either the element at index from the
list. The old element is returned.
// All elements following the removed element
are moved forward in the list.
ScriptObject SetObjectIntoList( ScriptObject, long
index, ScriptObject element )

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

156

// sets the element into the list at the given


index.
// If the index is out of range, nothing is
done.
// The old element at the index is returned.
long SizeOfList( ScriptObject )
// returns the number of elements in the list.
}
Global Image ID
DigitalMicrograph includes a class for handling global image id's.

class imageid : object{


void Init( object self, number one, number two,
number three, number four )
// initialize an imageid to the given values.
Boolean Compare( object self, id other )
// return true if the other imageid matches this
one.
void GetValues( object self, number &one, number
&two, number &three, number &four )
// return the underlying data making up this
globally unique identifier.
Boolean IsOpen( object self )
// return true if the image with the given
unique id is already open in DigitalMicrograph.
Boolean CanOpen( object self )
// return true if the image with the given
unique id is already open or openable from a
database.
Image Open( object self )
// return the image with the given unique id if
it is already open.
// If not, Open() will attempt to open it from
any associated database.
// If you want to only access an image that is
already in memory,
// be sure to check beforehand using the IsOpen
() method.
Copyright 2012 Gatan Inc. All Rights Reserved.

157

DigitalMicrograph

}
You can create an image id object via an image.

object ImageGetUniqueID( Image image )


Returns an image id object from the given image.
1.8.5.1

Threading

Threading
The DigitalMicrograph scripting language supports multiple threads.
You can start a thread by running the statement

StartThread( Object, MethodName )


MethodName is a string specifying the method to invoke on the object. It must be the name of
a method that takes no arguments and has no return value.
DigitalMicrograph also includes a class for managing threads. This overrides the old method
of including a "// $BACKGROUND$" line at the beginning of a script. The class is useful if you
need to more precisely control what happens when launching and finishing a method on a
class which you cannot modify.

class thread : object


{
void StartThread( ScriptObject )
Launch the thread into the background.

void RunThread( ScriptObject )


Override this method.

}
You should override the RunThread() method to implement the code you wish to run
in another thread.

class mythread : thread{


number myValue
object init( object self, number value )
{
myvalue = value
return self
}
void RunThread( object self )
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

158

{
number i
for ( i=0; i<myvalue; i++ )
{
result( myvalue+"\n" )
yield()
}
}
}
alloc(mythread).init(50).StartThread()
This script will start a thread that will print out the number "50" 50 times in the
background.

Message Queues
Message queues are used to send messages between threads. A message handler
thread will typically wait for a message to appear in the queue at which point it will
perform an action based on the message. Other threads will post messages to the
queue. The messages are represented as script objects.
To Create a Message Queue
To create a message queue, call the function NewMessageQueue.

object NewMessageQueue()
To Use a Message Queue
The message queue class defines several methods.

class MessageQueue
{
void PostMessage( object self, object message )
Causes any threads blocking on the message queue (via
WaitOnMessage) to unblock and return the message passed into
PostMessage.

object WaitOnMessage( object self )


Block the current thread until a message appears in the message
queue.

object WaitOnMessage( object self, number


timeout, object cancel_signal )
Block the current thread until a message appears in the message
queue. Allows for a timeout and a cancel signal object to cancel the
Copyright 2012 Gatan Inc. All Rights Reserved.

159

DigitalMicrograph

wait time. If WaitOnMessage is cancelled with a signal, an


exception is thrown in the thread that called WaitOnMessage.

}
Following is an example script that starts two threads that communicate with
each other through messages:

object mq = NewMessageQueue()
class myMessage : object
{
number myValue
object init( object self, number value )
{
myvalue = value
return self
}
number getValue( object self )
{
return myValue
}
number setValue( object self, number
value )
{
myvalue = value
}
}
class mythread : thread
{
number myValue
object messageTemplate
object init( object self, number value,
object message )
{
myvalue = value
messageTemplate = message
return self
}
void RunThread( object self )
{
number i
for ( i=0; i< myvalue; i++ )
{
result( i +"\n" )
object message = messageTemplate.
ScriptObjectClone()
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

160

message.SetValue( i )
mq.PostMessage( message )
sleep( 1 )
}
}
}
class mythread2 : thread
{
void RunThread( object self )
{
while( 1 ) {
object message = mq.WaitOnMessage( 2, null )
if ( message.ScriptObjectIsValid() ){
result( "received " +
message.getValue() +"\n" )
}
else{
result( "time out 2\n" )
return
}
}
}
}
object message = alloc( myMessage )
alloc(mythread).init(10, message ).StartThread()
alloc(mythread2).StartThread()
Note that in the above example all messages are saved in a queue. So if you
place a Sleep(5) statement between the starts of the two threads, then all the
messages will still be available for the second thread.
We can also add a second thread that waits on the same message. Each of
the waiting threads will pick up messages when they are available and
process them accordingly.

Synchronization
Signals
Signals can be used to interact between threads. A signal is either in an
unsignaled state or a signaled state. A thread can block on a signal in an
unsignaled state until it becomes signaled. The thread will use up no
processing time until the signal becomes signaled, is canceled, or times out.

Copyright 2012 Gatan Inc. All Rights Reserved.

161

DigitalMicrograph

To Create a Signal
To create a signal, call the function NewSignal or the NewCancelSignal
function which is the same as NewSignal(false).

object NewSignal( number initially_signaled )


object NewCancelSignal()
To Use a Signal
The signal class defines several methods.

class Signal
{
void SetSignal( ScriptObject self )
Causes any threads blocking on the signal to become unblocked. If
multiple threads are blocking on the signal they will become
unblocked in no particular order.

void ResetSignal( ScriptObject self )


Causes the signal to become unsignaled. Threads waiting on the
signal in the future will block until the signal becomes signaled or
canceled.

void WaitOnSignal( ScriptObject self, number


timeout, object cancel_signal )
Causes the current thread to block until the signal becomes
signaled, the time specified (in seconds) by the timeout parameter
has passed, or the signal object passed in as the cancel_signal is
signaled. The cancel_signal parameter may be null in which case
there is no way to cancel the thread. If this method times out, no
exception is thrown. If this method is canceled, a cancel error is
thrown in the thread in which it was called.

}
In the following example script, which is very similar to the example for
messageQueue, one thread sets a signal and two threads are waiting on the
signal and reset it when they finished processing. Note that in this example a
cancelSignal was used, unlike for the MessageQueue example, because there
is no way to otherwise have the threads finish. When the cancelSignal is set
by myThread1, an exception is thrown in the other two threads from the
WaitOnSignal() method. If this happens those threads are finished. Also the
two listening threads are started first, because otherwise they miss the first
time the signal is set. In the messageQueue example this was not necessary,
because the messages remained in the queue.

number false = 0, true = 1;

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

162

object startSignal = NewSignal( false )


object cancelSignal = NewSignal( false )
class mythread : thread
{
number myValue
object init( object self, number value )
{
myvalue = value
return self
}
void RunThread( object self )
{
number i
for ( i=0; i< myvalue; i++ )
{
result( i +"\n" )
startSignal.setSignal()
sleep( 1 )
}
cancelSignal.setSignal()
}
}
class mythread2 : thread
{
void RunThread( object self )
{
number do_break = false
while( true ) {
try
{
startSignal.waitonsignal
( infinity() , cancelSignal )
}
catch
{
do_break = true
break
}
if ( do_break )
break
startSignal.resetSignal()
result( "thread2 running\n" )
Copyright 2012 Gatan Inc. All Rights Reserved.

163

DigitalMicrograph

}
result( "thread2 cancelled\n" )
}
}
class mythread3 : thread
{
void RunThread( object self )
{
number do_break = false
while( true ) {
try
{
startSignal.waitonsignal
( infinity() , cancelSignal )
}
catch
{
do_break = true
break
}
if ( do_break )
break
startSignal.resetSignal()
result( "thread3 running\n" )
}
result( "thread3 cancelled\n" )
}
}
alloc(mythread2).StartThread( )
alloc(mythread3).StartThread( )
alloc(mythread).init( 10 ).StartThread()

Mutexes, Semaphores, and Critical Sections


Mutexes can be used to control mutually exclusive access to a resource between
threads. Mutexes are either in an unsignaled or a signaled state. A thread can block
on a mutex in an unsignaled state until it becomes signaled. A mutex is initially
created signaled. A mutex becomes unsignaled when it is acquired. It becomes
signaled when the thread that acquired it releases it.
Semaphores can be used to control access to a resource that has multiple instances.
Semaphores are either in an unsignaled or a signaled state. A thread can block on a
semaphore in an unsignaled state until it becomes signaled. A semaphore is created

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

164

with a count and is signaled whenever its count is greater than zero. A semaphore
becomes unsignaled when its count goes to zero. It becomes signaled when any
thread that acquired it releases it and causes its count to be greater than zero.
Critical sections can be used to ensure that only one thread is executing a particular
section of code. They are identical to mutexes except that critical sections do not
timeout. They may have slightly better performance than mutexes also.
To Create a Blocking Object
To create a blocking object, call one of the functions NewMutex,
NewSemaphore, or NewCriticalSection.

object NewMutex()
object NewSemaphore( number initial_count )
object NewCriticalSection()
To Use a Blocking Object
The blocking_objects class defines a few methods.

class blocking_objects
{
void acquire( ScriptObject self )
Causes the current thread to block until the blocking object
becomes signaled.

void acquire( ScriptObject self, number timeout,


object cancel_signal )
Causes the current thread to block until the blocking object
becomes signaled, the time specified (in seconds) by the timeout
parameter has passed, or the signal object passed in as the
cancel_signal is signaled. The cancel_signal parameter may be
null in which case there is no way to cancel the thread. If this
method times out, no exception is thrown. If this method is
canceled, a cancel error is thrown in the thread in which it was
called.

}
The following example expands on the example used for Signals. In this
example two threads are using the same object, and accessing the same
method in that object. To prevent the two threads from interfering with one
an other, the function uses a critical section. As currently written, the script
will print the squares from 1 to 20. If the critical section were not present,
both threads would print the same results, and only the odd squares would
be printed, each two times.

number false = 0, true = 1;


Copyright 2012 Gatan Inc. All Rights Reserved.

165

DigitalMicrograph

object startSignal = NewSignal( false )


object cancelSignal = NewSignal( false )
object globalCS = NewCriticalSection()
class squareObject : object
{
number myvalue
object init( object self, number value )
{
myvalue = value
return self
}
number getSquare( object self )
{
object cs = globalCS.Acquire()
number squareValue
squareValue = myvalue * myvalue
Sleep( 0.1 )
myvalue = myvalue + 1
return squareValue
}
}
class mythread : thread
{
number myValue
object init( object self, number value )
{
myvalue = value
return self
}
void RunThread( object self )
{
number i
for ( i=0; i< myvalue; i++ )
{
result( i +"\n" )
startSignal.setSignal()
sleep( 1 )
}
cancelSignal.setSignal()
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

166

}
}
class mythread2 : thread
{
object mySquare
object init( object self, object sq )
{
mySquare = sq
return self
}
void RunThread( object self )
{
number do_break = false
while( true ) {
try
{
startSignal.waitonsignal( infinity() ,
cancelSignal )
result( "thread2: " + mySquare.
GetSquare() + "\n" )
}
catch
{
do_break = true
break
}
if ( do_break )
break
startSignal.resetSignal()
}
result( "thread2 cancelled\n" )
}
}
class mythread3 : thread
{
object mySquare
object init( object self, object sq )
{
mySquare = sq
return self
}
Copyright 2012 Gatan Inc. All Rights Reserved.

167

DigitalMicrograph

void RunThread( object self )


{
number do_break = false
while( true ) {
try
{
startSignal.waitonsignal( infinity() ,
cancelSignal )
result( "thread3: " + mySquare.
GetSquare() + "\n" )
}
catch
{
do_break = true
break
}
if ( do_break )
break
startSignal.resetSignal()
}
result( "thread3 cancelled\n" )
}
}
object squaring = alloc( squareObject ).init( 1 )
alloc(mythread2).init( squaring ).StartThread( )
alloc(mythread3).init( squaring ).StartThread( )
alloc(mythread).init( 10 ).StartThread()

Tasks
Tasks can be set up with DigitalMicrograph to execute periodically or once. They are
guaranteed to be executed from the main thread.
To Register a Single Task
To register a single shot task (that may be delayed) call
AddMainThreadSingleTask.

Number AddMainThreadSingleTask( Object task,


String meth_name, Number delay_s )
The AddMainThreadSingleTask function sets up the method indicated by

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

168

meth_name to be invoked on the task object after the delay given by delay_s
(in seconds). The resulting task ID is returned.
To Register a Periodic Task
To register a periodic task call AddMainThreadPeriodicTask.

Number AddMainThreadPeriodicTask( Object task,


String meth_name, Number period_s )
The AddMainThreadPeriodicTask function sets up the method indicated by
meth_name to be invoked on the task object at a periodic of period_s (in
seconds). The resulting task ID is returned. You must call
RemoveMainThreadTask to stop this task.
To Remove a Periodic or Pending Task
To remove a periodic task or a pending task call RemoveMainThreadTask.

void RemoveMainThreadTask( Number task_id )


1.8.5.2

Event Handling

Event Handling
There are two classes for dealing with high-performance events: EventMap and
EventSource. An eventmap provides a mapping from between event names, event id's, and
methods. It serves as a list of possible events from a particular event source. An eventsource
is something to which to attach listeners. Events are fired out of the event source via the fire
event method which dispatches them to the methods in the event map.

class EventMap
{
boolean ConstructEventFlags( string
event_flags_description, number &event_flags );
boolean DesconstructEventFlags( number event_flags,
string &event_flags_description );
void AddEvent( number event_id, string event_name,
string method_signature );
}
class EventSource
{
number AddEventListener( ScriptObject listener,
string event_handler_description );
void RemoveEventListener( number attachment_id );
void ClearEventListeners();
Copyright 2012 Gatan Inc. All Rights Reserved.

169

DigitalMicrograph

}
ScriptObject NewEventSource( ScriptObject event_map,
string fire_event_method_name );
ScriptObject NewEventMap( string event_source_name );

Using Events
Here we will show the general way of using EventMap and EventSource. The example
below follows the procedure outlined here.
1. Create an eventmap that describes the mapping between event id's and events.
Construct an event map with the NewEventMap function. The
event_source_name is currently unused .
2. Add events to the event map with the AddEvent method.
event_id must be represented by a unique bit within a 32-bit word for each
event. event_name is a convenience name for the event. method_signature
represents the signature of the method that will be invoked on the listener.
3. Create an event source with the NewEventSource function.
Pass the newly created event_map and a string naming the firing method.
4. Declare an interface and substitute the firing method for each of the method
prototypes added via the AddEvent method.
This allows the script language to call your method.
5. Declare a listener class that implements functions with the same signature as used
in the AddEvent function of the EventMap.
6. Instantiate an object of the listener class.
7. Attach the listener to the EventSource with the function AddEventListener().
The event_handler_description consists of a list (separated by semicolons) of
event name/method name pairs (separated by colons). Note that the event
name has to match the event_name parameter used when adding events to
the EventMap.
8. Fire a method from the event source
By invoking the firing function on the event source, passing the event_id for the
desired event, a NULL, and the arguments to pass to the method associated
with the event id in the event map. The NULL is used as a placeholder for the
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

170

listener object internally when firing the event.


Example:

// declare an interface so we can use the firing


method "manipulated"
interface MyEventInterface{
void manipulated( object event_source, number
event_flag, object listener, number degrees
);
void manipulated( object event_source, number
event_flag, object listener );
}
// declare a listener class
class MyListener
{
void My_Twisted( object self, number degrees )
{
result( "Twisted by " + degrees + "
degrees\n" )
}
void My_Flipped( object self )
{
result( "Flipped\n" )
}
void AttachListener( object self, object es )
{
es.AddEventListener( self, "twisted:
My_Twisted;flipped:My_Flipped" )
}
}
// create a new eventmap
object em = NewEventMap( "com.gatan.
example_event_map" )
// add 2 events to the event map
em.AddEvent( 1, "twisted", "void method( ScriptObject
listener, uint32 degrees )" )
em.AddEvent( 2, "flipped", "void method( ScriptObject
listener )" )
// create a new eventsource

Copyright 2012 Gatan Inc. All Rights Reserved.

171

DigitalMicrograph

// the method "manipulated" is used as the firing


method
object es = NewEventSource( em, "manipulated" )
// create the listener
object listener = alloc( MyListener )
// make the listener listen to the eventsource
listener.AttachListener( es )
// fire some events in the eventsource
es.manipulated( 1, NULL, 14 ) // twisted 14 degrees
es.manipulated( 2, NULL ) // rotated
1.8.5.3

TagGroup Object

TagGroup Object
Tags and TagGroups are used throughout DigitalMicrograph to store data. For example, you
can view all the globally stored tags by opening the Global Info dialog and selecting General:
Tags in the left survey pane.
TagGroups can either contain name - value pairs, where the value can be virtually anything,
including other TagGroups, or they can contain indexed tags. In the latter case the TagGroup
is referred to as a TagList.
An easy way to visialize a TagGroup is to use the function

DocumentWindow TagGroupOpenBrowserWindow( TagGroup


tagGroup, Boolean isFileBased )
Once you have a TagGroup, you can call this function which will open a browser
window that shows the contents of the TagGroup.
For example:

TagGroup tg = NewTagGroup()
number index
index = tg.TagGroupCreateNewLabeledTag( "Street
Number" )
tg.TagGroupSetIndexedTagAsLong( index, 5933 )
index = tg.TagGroupCreateNewLabeledTag( "Street Name"
)
tg.TagGroupSetIndexedTagAsString( index, "Coronado
Lane" )

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

172

tg.TagGroupOpenBrowserWindow( 0 )
Note that when the tags are displayed they do not appear in the order specified, but
are ordered alphabetically.
If the order of tags is important, then one should use a TagList, as in this example:

TagGroup tg = NewTagList()
tg.TagGroupInsertTagAsLong( infinity(), 5933 )
tg.TagGroupInsertTagAsString( infinity(), "Coronado
Lane" )
tg.TagGroupOpenBrowserWindow( 0 )
Accessing existing TagGroups
The main TagGroups that already exist are the ones displayed in Global Info, and
TagGroups attached to images and imageDisplays. To access the global TagGroup
use the function

TagGroup GetPersistentTagGroup( )
as in the folowing example:

TagGroup tg = GetPersistentTagGroup( )
tg.TagGroupOpenBrowserWindow( 0 )
When running the above script you can view the same information as is presented in
the Global Info dialog.
Each Image and ImageDisplay also contain a TagGoup. You can access the
TagGroup associated with an image as in the following script:

Image img := GetFrontImage()


TagGroup tg = img.ImageGetTagGroup()
tg.TagGroupOpenBrowserWindow( 0 )
Traversing TagGroups
Given a TagGroup you may wish to find information in it. In the examples here we will
use the Global TagGroup.
The simplest case is where you know exactly where the tag is stored and what its
type is. For example, in the Global TagGroup there is a TagGroup with label
"Microscope Info"; in this group there is a tag with label "Voltage" that contains a
number. (You can set this tag by selecting Global Microscope Info from the
Copyright 2012 Gatan Inc. All Rights Reserved.

173

DigitalMicrograph

Microscope menu, and then enter a value under Beam Energy.) To access this tag
from script, use the following script:

TagGroup tg = GetPersistentTagGroup( )
number voltage
tg.TagGroupGetTagAsNumber( "Microscope Info:Voltage",
voltage )
Result("The Beam Energy = " + voltage + " V.\n" )
Note the string "Microscope Info:Voltage" which specifies the path to the tag.
You can also do the traversing in steps as follows:

TagGroup tg = GetPersistentTagGroup( )
number voltage
TagGroup infoTG
tg.TagGroupGetTagAsTagGroup( "Microscope Info",
infoTG )
infoTG.TagGroupGetTagAsNumber( "Voltage", voltage )
Result("The Beam Energy = " + voltage + " V.\n" )
If you do not know in advance what the tag labels are or their types, you are still able
to find tags. In the following example all tags contained in the "Microscope Info"
TagGroup are written to the results window:

tg.TagGroupGetTagAsTagGroup( "Microscope Info",


infoTG )
number count = infoTg.TagGroupCountTags( )
number i
for( i = 0; i < count; ++i )
{
String label = infoTG.TagGroupGetTagLabel( i )
number type = infoTG.TagGroupGetTagType( i, 0 )
if( type == 0 ) {
// tag is a TagGroup
Result(label + " = TagGroup\n" )
}
if( type == 2 ) {
// tag is a short
number value
infoTG.TagGroupGetTagAsShort( label, value )
Result(label + " = " + value + "\n" )
}
if( type == 3 ) {
// tag is a long
number value
infoTG.TagGroupGetTagAsLong( label, value )
Result(label + " = " + value + "\n" )
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

174

}
if( type == 6 ) {
// tag is a float
number value
infoTG.TagGroupGetTagAsFloat( label, value )
Result(label + " = " + value + "\n" )
}
if( type == 7 ) {
// tag is a double
number value
infoTG.TagGroupGetTagAsDouble( label, value )
Result(label + " = " + value + "\n" )
}
if( type == 8 ) {
// tag is a boolean
number value
infoTG.TagGroupGetTagAsBoolean( label,
value )
Result(label + " = " + value + "\n" )
}
if( type == 20 ) {
// tag is a string
string value
infoTG.TagGroupGetTagAsString( label, value )
Result(label + " = " + value + "\n" )
}
}
Note that in the above script we had to determine what the tag type was by using the
function

Number TagGroupGetTagType( TagGroup tagGroup, Number


index, Number type_index )
In this function type_index should be set to zero to receive the main tagType
information. After the type is known, the type specific TagGroupGetTagAsType()
function is used. (Not all the tagTypes are tested for in the example.)
To find out what all the tagTypes are you can run the example in section "Tag Types".
In this example other values of type-index are used to differentiate better between the
different TagTypes.

TagGroup Methods
TagGroup TagGroupAddLabeledTagGroup( TagGroup
tagGroup, String label, TagGroup newGroup )
Copyright 2012 Gatan Inc. All Rights Reserved.

175

DigitalMicrograph

Adds 'newGroup' to 'tagGroup' at the label 'label'.

TagGroup TagGroupAddTagGroupAfter( TagGroup tagList,


Number ref_index, TagGroup newGroup )
Adds 'newGroup' to 'tagList' after index 'ref_index'

TagGroup TagGroupAddTagGroupAtBeginning( TagGroup


tagList, TagGroup newGroup )
Adds 'newGroup' to the beginning of 'tagList'.

TagGroup TagGroupAddTagGroupAtEnd( TagGroup tagList,


TagGroup newGroup )
Adds 'newGroup' to the end of 'tagList'.

TagGroup TagGroupAddTagGroupBefore( TagGroup tagList,


Number ref_index, TagGroup newGroup )
Adds 'newGroup' to 'tagList' before index 'ref_index'.

TagGroup TagGroupClone( TagGroup tagGroup )


Returns an identical copy of 'tagGroup' and its sub-tags.

Number TagGroupCopyTag( TagGroup tagGroup, TagGroup


srcGroup, Number srcIndex )
Copies the 'srcIndex'th tag in 'srcGroup' to 'tagGroup'.

void TagGroupCopyTagsFrom( TagGroup tagGroup,


TagGroup srcGroup )
Copies tags in 'srcGroup' to 'tagGroup'.

void TagGroupCopyTagToIndex( TagGroup tagGroup,


Number dstIndex, TagGroup srcGroup, Number
srcIndex )
Copies data in the 'srcIndex'th tag in 'srcGroup' to the 'dstIndex'th tag in
'tagGroup'.

Number TagGroupCountTags( TagGroup tagGroup )


Returns the number of sub-tags in this tag group.

TagGroup TagGroupCreateGroupTagAfter( TagGroup


tagList, Number ref_index )
Creates a new tag group after 'ref_index' in 'tagList'.

TagGroup TagGroupCreateGroupTagAtBeginning( TagGroup


tagList )
Creates a new tag group at the beginning of 'tagList'.

TagGroup TagGroupCreateGroupTagAtEnd( TagGroup


tagList )
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

176

Creates a new tag group at the end of 'tagList'.

TagGroup TagGroupCreateGroupTagBefore( TagGroup


tagList, Number ref_index )
Creates a new tag group before 'ref_index' in 'tagList'.

TagGroup TagGroupCreateListTagAfter( TagGroup


tagList, Number ref_index )
Creates a new tag group after 'ref_index' in 'tagList'.

TagGroup TagGroupCreateListTagAtBeginning( TagGroup


tagList )
Creates a new tag group at the beginning of 'tagList'.

TagGroup TagGroupCreateListTagAtEnd( TagGroup tagList


)
Creates a new tag group at the end of 'tagList'.

TagGroup TagGroupCreateListTagBefore( TagGroup


tagList, Number ref_index )
Creates a new tag group before 'ref_index' in 'tagList'.

TagGroup TagGroupCreateNewLabeledGroup( TagGroup


tagGroup, String label )
Adds a new tag group at label 'label' and returns the new group.

TagGroup TagGroupCreateNewLabeledList( TagGroup


tagGroup, String label )
Adds a new tag list at label 'label' and returns the new group.

Number TagGroupCreateNewLabeledTag( TagGroup


tagGroup, String label )
Creates a new labeled tag and returns its index.

Number TagGroupCreateNewTagAfter( TagGroup tagList,


Number ref_index )
Creates a new tag after 'ref_index' in 'tagList'.

Number TagGroupCreateNewTagAtBeginning( TagGroup


tagList )
Creates a new tag at the beginning of 'tagList'.

Number TagGroupCreateNewTagAtEnd( TagGroup tagList )


Creates a new tag at the end of 'tagList'.

Number TagGroupCreateNewTagBefore( TagGroup tagList,


Number ref_index )
Creates a new tag before 'ref_index' in 'tagList'.
Copyright 2012 Gatan Inc. All Rights Reserved.

177

DigitalMicrograph

void TagGroupDeleteAllTags( TagGroup tagGroup )


Deletes all the tags in 'tagGroup'.

void TagGroupDeleteTagWithIndex( TagGroup taGroup,


Number index )
Deletes the tag at index 'index'.

void TagGroupDeleteTagWithLabel( TagGroup tagGroup,


String tagPath )
Deletes the tag labelled by the path 'tagPath'.

Boolean TagGroupDoesTagExist( TagGroup tagGroup,


String tagPath )
Finds the tag group and index corresponding to the tag referenced by 'tagPath'
in 'tagGroup'.

void TagGroupExecuteScriptGroup( TagGroup tagGroup,


String form )
Execute a group of script functions in 'tagGroup'. The actual scripts executed
will be formed by sprintf'ing into the 'form' parameter. The form parameter
should contain exactly one '%s' into which the function name will be inserted.

Boolean TagGroupGetIndexedTagAsArray( TagGroup


tagGroup, Number index, ImageReference image )
Gets the data at 'index' in 'tagGroup' as an array of data in 'image'.

Boolean TagGroupGetIndexedTagAsBoolean( TagGroup


tagGroup, Number index, NumberVariable val )
Gets the data at 'index' in 'tagGroup' as a boolean.

Boolean TagGroupGetIndexedTagAsDouble( TagGroup


tagGroup, Number index, NumberVariable number )
Gets the data at 'index' in 'tagGroup' as a double.

Boolean TagGroupGetIndexedTagAsDoubleComplex
( TagGroup tagGroup, Number index,
ComplexNumberVariable c )
Gets the data at 'index' in 'tagGroup' as a double complex.

Boolean TagGroupGetIndexedTagAsEightBitColor
( TagGroup tagGroup, Number index,
RGBNumberVariable c )
Gets the data at 'index' in 'tagGroup' as an eight bit color.

Boolean TagGroupGetIndexedTagAsFloat( TagGroup


tagGroup, Number index, NumberVariable number )
Gets the data at 'index' in 'tagGroup' as a float.
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

178

Boolean TagGroupGetIndexedTagAsFloatComplex( TagGroup


tagGroup, Number index, ComplexNumberVariable
c )
Gets the data at 'index' in 'tagGroup' as a float complex.

Boolean TagGroupGetIndexedTagAsFloatPoint( TagGroup


tagGroup, Number index, NumberVariable x,
NumberVariable y )
Gets the data at 'index' in 'tagGroup' as a float point.

Boolean TagGroupGetIndexedTagAsFloatRect( TagGroup


tagGroup, Number index, NumberVariable t,
NumberVariable l, NumberVariable b,
NumberVariable r )
Gets the data at 'index' in 'tagGroup' as a float rect.

Boolean TagGroupGetIndexedTagAsLong( TagGroup


tagGroup, Number index, NumberVariable number )
Gets the data at 'index' in 'tagGroup' as a long.

Boolean TagGroupGetIndexedTagAsLongPoint( TagGroup


tagGroup, Number index, NumberVariable x,
NumberVariable y )
Gets the data at 'index' in 'tagGroup' as a long point.

Boolean TagGroupGetIndexedTagAsLongRect( TagGroup


tagGroup, Number index, NumberVariable t,
NumberVariable l, NumberVariable b,
NumberVariable r )
Gets the data at 'index' in 'tagGroup' as a long rect.

Boolean TagGroupGetIndexedTagAsNumber( TagGroup


tagGroup, Number index, NumberVariable number )
Gets the data at 'index' in 'tagGroup' as a real number.

Boolean TagGroupGetIndexedTagAsNumber( TagGroup


tagGroup, Number index, ComplexNumberVariable
number )
Gets the data at 'index' in 'tagGroup' as a complex number.

Boolean TagGroupGetIndexedTagAsNumber( TagGroup


tagGroup, Number index, RGBNumberVariable number
)
Gets the data at 'index' in 'tagGroup' as a RGB number.

Copyright 2012 Gatan Inc. All Rights Reserved.

179

DigitalMicrograph

Boolean TagGroupGetIndexedTagAsShort( TagGroup


tagGroup, Number index, NumberVariable number )
Gets the data at 'index' in 'tagGroup' as a short.

Boolean TagGroupGetIndexedTagAsShortPoint( TagGroup


tagGroup, Number index, NumberVariable x,
NumberVariable y )
Gets the data at 'index' in 'tagGroup' as a short point.

Boolean TagGroupGetIndexedTagAsShortRect( TagGroup


tagGroup, Number index, NumberVariable t,
NumberVariable l, NumberVariable b,
NumberVariable r )
Gets the data at 'index' in 'tagGroup' as a short rect.

Boolean TagGroupGetIndexedTagAsString( TagGroup


tagGroup, Number index, String str )
Gets the data at 'index' in 'tagGroup' as a string.

Boolean TagGroupGetIndexedTagAsTagGroup( TagGroup


tagGroup, Number index, TagGroup subGroup )
Gets the data at 'index' in 'TagGroup' as a group.

Boolean TagGroupGetIndexedTagAsText( TagGroup


tagGroup, Number index, String str )
Gets the data at 'index' in 'tagGroup' as a string.

Boolean TagGroupGetIndexedTagAsUInt16( TagGroup


tagGroup, Number index, NumberVariable number )
Gets the data at 'index' in 'tagGroup' as a 16-bit unsigned integer.

Boolean TagGroupGetIndexedTagAsUInt32( TagGroup


tagGroup, Number index, NumberVariable number )
Gets the data at 'index' in 'tagGroup' as a 32-bit unsigned integer.

TagGroup TagGroupGetOrCreateTagGroup( TagGroup


tagGroup, String tagPath )
Gets the tag group named by 'tagPath', or creates a new such group and all
necessary intermediate groups.

TagGroup TagGroupGetOrCreateTagList( TagGroup


tagGroup, String tagPath )
Gets the tag list named by 'tagPath', or creates a new such list and all
necessary intermediate groups.

Number TagGroupGetSeeds( TagGroup tagGroup )


Gets a set of seeds that describe the tag group.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

180

Boolean TagGroupGetTagAsArray( TagGroup tagGroup,


String tagPath, ImageReference image )
Gets the data at 'tagPath' in 'tagGroup' as an array of data in 'image'.

Boolean TagGroupGetTagAsBoolean( TagGroup tagGroup,


String tagPath, NumberVariable val )
Gets the data at 'tagPath' in 'tagGroup' as a boolean.

Boolean TagGroupGetTagAsDouble( TagGroup tagGroup,


String tagPath, NumberVariable number )
Gets the data at 'tagPath' in 'tagGroup' as a double.

Boolean TagGroupGetTagAsDoubleComplex( TagGroup


tagGroup, String tagPath, ComplexNumberVariable
c )
Gets the data at 'tagPath' in 'tagGroup' as a double complex.

Boolean TagGroupGetTagAsEightBitColor( TagGroup


tagGroup, String tagPath, RGBNumberVariable c )
Gets the data at 'tagPath' in 'tagGroup' as an eight bit color.

Boolean TagGroupGetTagAsFloat( TagGroup tagGroup,


String tagPath, NumberVariable number )
Gets the data at 'tagPath' in 'tagGroup' as a float.

Boolean TagGroupGetTagAsFloatComplex( TagGroup


tagGroup, String tagPath, ComplexNumberVariable
c )
Gets the data at 'tagPath' in 'tagGroup' as a float complex.

Boolean TagGroupGetTagAsFloatPoint( TagGroup


tagGroup, String tagPath, NumberVariable x,
NumberVariable y )
Gets the data at 'tagPath' in 'tagGroup' as a short point.

Boolean TagGroupGetTagAsFloatRect( TagGroup tagGroup,


String tagPath, NumberVariable t, NumberVariable
l, NumberVariable b, NumberVariable r )
Gets the data at 'tagPath' in 'tagGroup' as a short rect.

Boolean TagGroupGetTagAsLong( TagGroup tagGroup,


String tagPath, NumberVariable number )
Gets the data at 'tagPath' in 'tagGroup' as a long.

Boolean TagGroupGetTagAsLongPoint( TagGroup tagGroup,


String tagPath, NumberVariable x, NumberVariable
y )
Gets the data at 'tagPath' in 'tagGroup' as a long point.
Copyright 2012 Gatan Inc. All Rights Reserved.

181

DigitalMicrograph

Boolean TagGroupGetTagAsLongRect( TagGroup tagGroup,


String tagPath, NumberVariable t, NumberVariable
l, NumberVariable b, NumberVariable r )
Gets the data at 'tagPath' in 'tagGroup' as a long rect.

Boolean TagGroupGetTagAsNumber( TagGroup tagGroup,


String tagPath, ComplexNumberVariable number )
Gets the data at 'tagPath' in 'tagGroup' as a complex number.

Boolean TagGroupGetTagAsNumber( TagGroup tagGroup,


String tagPath, NumberVariable number )
Gets the data at 'tagPath' in 'tagGroup' as a real number.

Boolean TagGroupGetTagAsNumber( TagGroup tagGroup,


String tagPath, RGBNumberVariable number )
Gets the data at 'tagPath' in 'tagGroup' as a rgb number.

Boolean TagGroupGetTagAsRGBUInt16( TagGroup tagGroup,


Number index, NumberVariable r, NumberVariable
g, NumberVariable b )
Gets the data at 'index' in 'tagGroup' as a 16-bit rgb value.

Boolean TagGroupGetTagAsRGBUInt16( TagGroup tagGroup,


String tagPath, NumberVariable r, NumberVariable
g, NumberVariable b )
Gets the data at 'tagPath' in 'tagGroup' as a 16-bit rgb value.

Boolean TagGroupGetTagAsShort( TagGroup tagGroup,


String tagPath, NumberVariable number )
Gets the data at 'tagPath' in 'tagGroup' as a short.

Boolean TagGroupGetTagAsShortPoint( TagGroup


tagGroup, String tagPath, NumberVariable x,
NumberVariable y )
Gets the data at 'tagPath' in 'tagGroup' as a short point.

Boolean TagGroupGetTagAsShortRect( TagGroup tagGroup,


String tagPath, NumberVariable t, NumberVariable
l, NumberVariable b, NumberVariable r )
Gets the data at 'tagPath' in 'tagGroup' as a short rect.

Boolean TagGroupGetTagAsString( TagGroup tagGroup,


String tagPath, String str )
Gets the data at 'tagPath' in 'tagGroup' as a string.

Boolean TagGroupGetTagAsTagGroup( TagGroup tagGroup,


String tagPath, TagGroup subGroup )
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

182

Gets the data at 'tagPath' in 'TagGroup' as a group.

Boolean TagGroupGetTagAsText( TagGroup tagGroup,


String tagPath, String str )
Gets the data at 'tagPath' in 'tagGroup' as a string.

Boolean TagGroupGetTagAsUInt16( TagGroup tagGroup,


String tagPath, NumberVariable number )
Gets the data at 'tagPath' in 'tagGroup' as a 16-bit unsigned integer.

Boolean TagGroupGetTagAsUInt32( TagGroup tagGroup,


String tagPath, NumberVariable number )
Gets the data at 'tagPath' in 'tagGroup' as a 32-bit unsigned integer.

String TagGroupGetTagLabel( TagGroup tagGroup, Number


index )
Gets the label of the 'index'th tag in the tag group.

Number TagGroupGetTagSize( TagGroup tagGroup, Number


index )
Gets the size of the tag.

Number TagGroupGetTagType( TagGroup tagGroup, Number


index, Number type_index )
Returns the 'type_index'th element of the tag's type.

Number TagGroupGetTagTypeLength( TagGroup tagGroup,


Number index )
Returns number of elements in the tag's type.

Boolean TagGroupHasChangedSince( TagGroup tagGroup,


Number seeds )
Returns true if the tag group has changed since 'seeds' was constructed.

void TagGroupInsertTagAsArray( TagGroup tagGroup,


Number ref_index, ImageReference image )
Inserts new data before 'ref_index' in 'tagGroup' as an array of data in 'image'.

void TagGroupInsertTagAsBoolean( TagGroup tagGroup,


Number ref_index, Boolean val )
Inserts new data before 'ref_index' in 'tagGroup' as a boolean.

void TagGroupInsertTagAsDouble( TagGroup tagGroup,


Number ref_index, Number number )
Inserts new data before 'ref_index' in 'tagGroup' as a double.

void TagGroupInsertTagAsDoubleComplex( TagGroup


tagGroup, Number ref_index, ComplexNumber c )
Copyright 2012 Gatan Inc. All Rights Reserved.

183

DigitalMicrograph

Inserts new data before 'ref_index' in 'tagGroup' as a double complex.

void TagGroupInsertTagAsEightBitColor( TagGroup


tagGroup, Number ref_index, RGBNumber c )
Inserts new data before 'ref_index' in 'tagGroup' as an eight bit color.

void TagGroupInsertTagAsFloat( TagGroup tagGroup,


Number ref_index, Number number )
Inserts new data before 'ref_index' in 'tagGroup' as a float.

void TagGroupInsertTagAsFloatComplex( TagGroup


tagGroup, Number ref_index, ComplexNumber c )
Inserts new data before 'ref_index' in 'tagGroup' as a float complex.

void TagGroupInsertTagAsFloatPoint( TagGroup


tagGroup, Number ref_index, Number x, Number
y )
Inserts new data before 'ref_index' in 'tagGroup' as a float point.

void TagGroupInsertTagAsFloatRect( TagGroup tagGroup,


Number ref_index, Number t, Number l, Number b,
Number r )
Inserts new data before 'ref_index' in 'tagGroup' as a float rect.

void TagGroupInsertTagAsLong( TagGroup tagGroup,


Number ref_index, Number number )
Inserts new data before 'ref_index' in 'tagGroup' as a long.

void TagGroupInsertTagAsLongPoint( TagGroup tagGroup,


Number ref_index, Number x, Number y )
Inserts new data before 'ref_index' in 'tagGroup' as a long point.

void TagGroupInsertTagAsLongRect( TagGroup tagGroup,


Number ref_index, Number t, Number l, Number b,
Number r )
Inserts new data before 'ref_index' in 'tagGroup' as a long rect.

void TagGroupInsertTagAsNumber( TagGroup tagGroup,


Number ref_index, RGBNumber number )
Inserts new data before 'ref_index' in 'tagGroup' as a RGB number.

void TagGroupInsertTagAsNumber( TagGroup tagGroup,


Number ref_index, ComplexNumber number )
Inserts new data before 'ref_index' in 'tagGroup' as a complex number.

void TagGroupInsertTagAsNumber( TagGroup tagGroup,


Number ref_index, Number number )
Inserts new data before 'ref_index' in 'tagGroup' as a real number.
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

184

void TagGroupInsertTagAsRGBUInt16( TagGroup tagGroup,


Number ref_index, Number r, Number g, Number
b )
Inserts new data before 'ref_index' in 'tagGroup' as a 16-bit rgb value.

void TagGroupInsertTagAsShort( TagGroup tagGroup,


Number ref_index, Number number )
Inserts new data before 'ref_index' in 'tagGroup' as a short.

void TagGroupInsertTagAsShortPoint( TagGroup


tagGroup, Number ref_index, Number x, Number
y )
Inserts new data before 'ref_index' in 'tagGroup' as a short point.

void TagGroupInsertTagAsShortRect( TagGroup tagGroup,


Number ref_index, Number t, Number l, Number b,
Number r )
Inserts new data before 'ref_index' in 'tagGroup' as a short rect.

void TagGroupInsertTagAsString( TagGroup tagGroup,


Number ref_index, String s )
Inserts new data before 'ref_index' in 'tagGroup' as a string.

void TagGroupInsertTagAsTagGroup( TagGroup tagGroup,


Number ref_index, TagGroup subGroup )
Inserts new data before 'ref_index' in 'TagGroup' as a group.

void TagGroupInsertTagAsText( TagGroup tagGroup,


Number ref_index, String s )
Inserts new data before 'ref_index' in 'tagGroup' as a string.

void TagGroupInsertTagAsUInt16( TagGroup tagGroup,


Number ref_index, Number number )
Inserts new data before 'ref_index' in 'tagGroup' as a 16-bit unsigned integer.

void TagGroupInsertTagAsUInt32( TagGroup tagGroup,


Number ref_index, Number number )
Inserts new data before 'ref_index' in 'tagGroup' as a 32-bit unsigned integer.

Boolean TagGroupIsList( TagGroup tagGroup )


Returns true if the tag group is a list.

Boolean TagGroupIsOpen( TagGroup tagGroup )


Returns whether 'tagGroup' is open or not.

Boolean TagGroupIsValid( TagGroup tagGroup )


Returns true if 'tagGroup' references a valid object.
Copyright 2012 Gatan Inc. All Rights Reserved.

185

DigitalMicrograph

Boolean TagGroupLoadFromFile( TagGroup tagGroup,


String path )
Loads the contents of the file specified by 'path' into the tag group.

Boolean TagGroupLoadFromFileWithLabel( TagGroup


tagGroup, String path, String label )
Loads the contents of the file specified by 'path' into the tag group and returns
the label, if any.

Boolean TagGroupLoadFromStream( TagGroup tagGroup,


ScriptObject stream )
Loads the contents of the stream specified by 'stream' into the tag group.

Boolean TagGroupLoadFromStreamWithLabel( TagGroup


tagGroup, ScriptObject stream, String label )
Loads the contents of the stream specified by 'stream' into the tag group and
returns the label, if any.

void TagGroupMarkAsChanged( TagGroup tagGroup )


Marks 'tagGroup' as having beein modified.

DocumentWindow TagGroupOpenBrowserWindow( TagGroup


tagGroup, Boolean isFileBased )
Opens a browser window for the tag group.

Number TagGroupParseAndCreateTagPath( TagGroup


tagGroup, String tagPath, TagGroup parentGroup,
String label )
Finds the tag group and index corresponding to the tag referenced by 'tagPath'
in 'tagGroup'.

Number TagGroupParseTagPath( TagGroup tagGroup,


String tagPath, TagGroup parentGroup, String
label )
Finds the tag group and index corresponding to the tag referenced by 'tagPath'
in 'tagGroup'.

void TagGroupReadIndexedTagDataFromStream( TagGroup


tagGroup, Number index, ScriptObject stream,
Number stream_endianness )
Reads data from the stream into the indicated tag. The tag type determines
how the data is read, and 'stream_endianness' specifies the endianness of the
stream, 1 == bigendian, 2 == littleendian.

void TagGroupReadTagDataFromStream( TagGroup


tagGroup, String tag_path, ScriptObject stream,
Number stream_endianness )
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

186

Reads data from the stream into the indicated tag. The tag type determines
how the data is read, and 'stream_endianness' specifies the endianness of the
stream, 1 == bigendian, 2 == littleendian.

void TagGroupReleaseSeeds( TagGroup tagGroup, Number


seeds )
Releases the seeds returned by 'TagGroupGetSeeds'.

void TagGroupReplaceTagsWithCopy( TagGroup tagGroup,


TagGroup srcGroup )
Deletes all tags in 'tagGroup' and copies tags in 'srcGroup' to 'tagGroup'.

void TagGroupSaveToFile( TagGroup tagGroup, String


path )
Saves the contents of the tag group to the file specified by 'path'.

void TagGroupSaveToFileWithLabel( TagGroup tagGroup,


String path, String label )
Saves the contents of the tag group and the label
'label' to the file specified by 'path'.
void TagGroupSaveToStream( TagGroup tagGroup,
ScriptObject stream )
Saves the contents of the tag group to the stream specified by 'stream'.

void TagGroupSaveToStreamWithLabel( TagGroup


tagGroup, ScriptObject stream, String label )
Saves the contents of the tag group and the label 'label' to the stream
specified by 'stream'.

void TagGroupSetIndexedTagAsArray( TagGroup tagGroup,


Number index, ImageReference image )
Set the data at 'index' in 'tagGroup' as an array of data in 'image'.

void TagGroupSetIndexedTagAsBoolean( TagGroup


tagGroup, Number index, Boolean val )
Sets the data at 'index' in 'tagGroup' as a boolean.

void TagGroupSetIndexedTagAsDouble( TagGroup


tagGroup, Number index, Number number )
Sets the data at 'index' in 'tagGroup' as a double.

void TagGroupSetIndexedTagAsDoubleComplex( TagGroup


tagGroup, Number index, ComplexNumber c )
Sets the data at 'index' in 'tagGroup' as a double complex.

void TagGroupSetIndexedTagAsEightBitColor( TagGroup


tagGroup, Number index, RGBNumber c )
Copyright 2012 Gatan Inc. All Rights Reserved.

187

DigitalMicrograph

Sets the data at 'index' in 'tagGroup' as an eight bit color.

void TagGroupSetIndexedTagAsFloat( TagGroup tagGroup,


Number index, Number number )
Sets the data at 'index' in 'tagGroup' as a float.

void TagGroupSetIndexedTagAsFloatComplex( TagGroup


tagGroup, Number index, ComplexNumber c )
Sets the data at 'index' in 'tagGroup' as a float complex.

void TagGroupSetIndexedTagAsFloatPoint( TagGroup


tagGroup, Number index, Number x, Number y )
Sets the data at 'index' in 'tagGroup' as a float point.

void TagGroupSetIndexedTagAsFloatRect( TagGroup


tagGroup, Number index, Number t, Number l,
Number b, Number r )
Sets the data at 'index' in 'tagGroup' as a float rect.

void TagGroupSetIndexedTagAsLong( TagGroup tagGroup,


Number index, Number number )
Sets the data at 'index' in 'tagGroup' as a long.

void TagGroupSetIndexedTagAsLongPoint( TagGroup


tagGroup, Number index, Number x, Number y )
Sets the data at 'index' in 'tagGroup' as a long point.

void TagGroupSetIndexedTagAsLongRect( TagGroup


tagGroup, Number index, Number t, Number l,
Number b, Number r )
Sets the data at 'index' in 'tagGroup' as a long rect.

void TagGroupSetIndexedTagAsNumber( TagGroup


tagGroup, Number index, RGBNumber number )
Sets the data at 'index' in 'tagGroup' as a RGB number.

void TagGroupSetIndexedTagAsNumber( TagGroup


tagGroup, Number index, ComplexNumber number )
Sets the data at 'index' in 'tagGroup' as a complex number.

void TagGroupSetIndexedTagAsNumber( TagGroup


tagGroup, Number index, Number number )
Sets the data at 'index' in 'tagGroup' as a real number.

void TagGroupSetIndexedTagAsRGBUInt16( TagGroup


tagGroup, Number index, Number r, Number g,
Number b )
Sets the data at 'index' in 'tagGroup' as a 16-bit rgb value.
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

188

void TagGroupSetIndexedTagAsShort( TagGroup tagGroup,


Number index, Number number )
Sets the data at 'index' in 'tagGroup' as a short.

void TagGroupSetIndexedTagAsShortPoint( TagGroup


tagGroup, Number index, Number x, Number y )
Sets the data at 'index' in 'tagGroup' as a short point.

void TagGroupSetIndexedTagAsShortRect( TagGroup


tagGroup, Number index, Number t, Number l,
Number b, Number r )
Sets the data at 'index' in 'tagGroup' as a short rect.

void TagGroupSetIndexedTagAsString( TagGroup


tagGroup, Number index, String s )
Sets the data at 'index' in 'tagGroup' as a string.

void TagGroupSetIndexedTagAsTagGroup( TagGroup


tagGroup, Number index, TagGroup subGroup )
Sets the data at 'index' in 'TagGroup' as a group.

void TagGroupSetIndexedTagAsText( TagGroup tagGroup,


Number index, String s )
Sets the data at 'index' in 'tagGroup' as a string.

void TagGroupSetIndexedTagAsUInt16( TagGroup


tagGroup, Number index, Number number )
Sets the data at 'index' in 'tagGroup' as a 16-bit unsigned integer.

void TagGroupSetIndexedTagAsUInt32( TagGroup


tagGroup, Number index, Number number )
Sets the data at 'index' in 'tagGroup' as a 32-bit unsigned integer.

void TagGroupSetIsOpen( TagGroup tagGroup, Boolean


is_open )
Sets whether 'tagGroup' is open or not.

void TagGroupSetTagAsArray( TagGroup tagGroup, String


tagPath, ImageReference image )
Set the data at 'tagPath' in 'tagGroup' as an array of data in 'image'.

void TagGroupSetTagAsBoolean( TagGroup tagGroup,


String tagPath, Boolean val )
Sets the data at 'tagPath' in 'tagGroup' as a boolean.

void TagGroupSetTagAsDouble( TagGroup tagGroup,


String tagPath, Number number )
Copyright 2012 Gatan Inc. All Rights Reserved.

189

DigitalMicrograph

Sets the data at 'tagPath' in 'tagGroup' as a double.

void TagGroupSetTagAsDoubleComplex( TagGroup


tagGroup, String tagPath, ComplexNumber c )
Sets the data at 'tagPath' in 'tagGroup' as a double complex.

void TagGroupSetTagAsEightBitColor( TagGroup


tagGroup, String tagPath, RGBNumber c )
Sets the data at 'tagPath' in 'tagGroup' as an eight bit color.

void TagGroupSetTagAsFloat( TagGroup tagGroup, String


tagPath, Number number )
Sets the data at 'tagPath' in 'tagGroup' as a float.

void TagGroupSetTagAsFloatComplex( TagGroup tagGroup,


String tagPath, ComplexNumber c )
Sets the data at 'tagPath' in 'tagGroup' as a float complex.

void TagGroupSetTagAsFloatPoint( TagGroup tagGroup,


String tagPath, Number x, Number y )
Sets the data at 'tagPath' in 'tagGroup' as a float point.

void TagGroupSetTagAsFloatRect( TagGroup tagGroup,


String tagPath, Number t, Number l, Number b,
Number r )
Sets the data at 'tagPath' in 'tagGroup' as a float rect.

void TagGroupSetTagAsLong( TagGroup tagGroup, String


tagPath, Number number )
Sets the data at 'tagPath' in 'tagGroup' as a long.

void TagGroupSetTagAsLongPoint( TagGroup tagGroup,


String tagPath, Number x, Number y )
Sets the data at 'tagPath' in 'tagGroup' as a long point.

void TagGroupSetTagAsLongRect( TagGroup tagGroup,


String tagPath, Number t, Number l, Number b,
Number r )
Sets the data at 'tagPath' in 'tagGroup' as a long rect.

void TagGroupSetTagAsNumber( TagGroup tagGroup,


String tagPath, RGBNumber number )
Sets the data at 'tagPath' in 'tagGroup' as a RGB number.

void TagGroupSetTagAsNumber( TagGroup tagGroup,


String tagPath, ComplexNumber number )
Sets the data at 'tagPath' in 'tagGroup' as a complex number.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

190

void TagGroupSetTagAsNumber( TagGroup tagGroup,


String tagPath, Number number )
Sets the data at 'tagPath' in 'tagGroup' as a real number.

void TagGroupSetTagAsRGBUInt16( TagGroup tagGroup,


String tagPath, Number r, Number g, Number b )
Sets the data at 'tagPath' in 'tagGroup' as a 16-bit rgb value.

void TagGroupSetTagAsShort( TagGroup tagGroup, String


tagPath, Number number )
Sets the data at 'tagPath' in 'tagGroup' as a short.

void TagGroupSetTagAsShortPoint( TagGroup tagGroup,


String tagPath, Number x, Number y )
Sets the data at 'tagPath' in 'tagGroup' as a short point.

void TagGroupSetTagAsShortRect( TagGroup tagGroup,


String tagPath, Number t, Number l, Number b,
Number r )
Sets the data at 'tagPath' in 'tagGroup' as a short rect.

void TagGroupSetTagAsString( TagGroup tagGroup,


String tagPath, String s )
Sets the data at 'tagPath' in 'tagGroup' as a string.

void TagGroupSetTagAsTagGroup( TagGroup tagGroup,


String tagPath, TagGroup subGroup )
Sets the data at 'tagPath' in 'TagGroup' as a group.

void TagGroupSetTagAsText( TagGroup tagGroup, String


tagPath, String s )
Sets the data at 'tagPath' in 'tagGroup' as a string.

void TagGroupSetTagAsUInt16( TagGroup tagGroup,


String tagPath, Number number )
Sets the data at 'tagPath' in 'tagGroup' as a 16-bit unsigned integer.

void TagGroupSetTagAsUInt32( TagGroup tagGroup,


String tagPath, Number number )
Sets the data at 'tagPath' in 'tagGroup' as a 32-bit unsigned integer.

void TagGroupSetTagRGBBitmap( TagGroup tagGroup,


String tagPath, ImageReference image )
Sets the data at 'tagPath' in 'tagGroup' as a RGB bitmap.

void TagGroupWriteIndexedTagDataToStream( TagGroup


tagGroup, Number index, ScriptObject stream,
Number stream_endianness )
Copyright 2012 Gatan Inc. All Rights Reserved.

191

DigitalMicrograph

Writes data from the indicated tag into the stream. The tag type determines
how the data is written, and 'stream_endianness' specifies the endianness of
the stream, 1 == bigendian, 2 == littleendian.

void TagGroupWriteTagDataToStream( TagGroup tagGroup,


String tag_path, ScriptObject stream, Number
stream_endianness )
Reads data from the indicated tag into the stream. The tag type determines
how the data is written, and 'stream_endianness' specifies the endianness of
the stream, 1 == bigendian, 2 == littleendian.

Related Functions
TagGroup =( TagGroup tagGroup1, ! )
TagGroup =( TagGroup tagGroup1, TagGroup tagGroup2 )
void AddTagsToPackage( TagGroup tags, String
packageName, Number packageLevel, String
identifier )
Install the tags into the package. The identifier is used to identify the tags in the
packages. Clients should take care to use unique identifiers. See the Java
model of naming classes.

void ClipboardSetAsTagGroup( TagGroup tagGroup )


Sets the contents of the clipboard to the tag group.

TagGroup GetFilesInDirectory( String path, Number


search_flags )
Returns a tag group containing a list of the file names in the directory
'dir_path'

TagGroup GetPackageTags( String identifier )


Return the tags specified by identifier. The identifier is used to identify tags
loaded with a specific package.

TagGroup GetPersistentTagGroup( )
Gets the persistent tag group.

TagGroup NewTagGroup( )
Creates an empty tag group.

TagGroup NewTagList( )
Creates an empty tag list.

TagGroup TagGroupNullify( ! )

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

192

TagGroup Test_ReferenceCount_V1( ROI roi_out )


TagGroup Test_ReferenceCount_V2( ROI roi_out )
1.8.5.4

Menus

Menus
The menu system of DigitalMicrograph can be completely controlled through scripts.
The menu system is comprised of a set of classes which allow you to manipulate the menu
system. The classes are:

MenuBar
Menu
MenuItem
Action
Keystroke
MenuAccelerator
DigitalMicrograph contains a single menu bar. The menu bar contains menus. Menus contain
other menus or menu items. Menu items can be selectable menu items or separators. Menu
items have various attributes that can be set. Selectable menu items also have an action
associated with them. Accelerators can be attached to specific menu items or to the menu
bar itself. Accelerators can be specified by a single character or by a keystroke.
The function GetMenuBar() returns DigitalMicrograph's menu bar.

Menu Bar
The menu bar object has the following interface:

Display menuBar
{
void AddAccelerator( Display menu_bar, object
accelerator )
Add the given accelerator to the menu bar's list of accelerators.
Accelerators associated with the menu bar are not associated with a specific
menu item. Use RemoveAccelerator to remove the accelerator from the menu
bar's list of accelerators.

object AddMenu( Display menu_bar, Display menu )


Add the given menu to the menu bar.

number AddMenuBarListener( Display menu_bar, object


listener, string event_descriptor )
Add the listener object to the menu bar. An id representing the listener
connection is returned. To remove the listener, use the
Copyright 2012 Gatan Inc. All Rights Reserved.

193

DigitalMicrograph

RemoveMenuBarListener function and pass in the id.

object AddMenuItem( Display menu_bar, Display menu,


object ref_menu )
Add the menu before the menu specified by the ref_menu parameter. Use the
RemoveMenuItem function to remove the menu item.

void ClearMenuBar( Display menu_bar )


Delete all menus from the menu bar.

object FindMenuItemByName( Display menu_bar, string


menu_name )
Return the menu with the given name.

number GetAccelerators( Display menu_bar, number


start_index, number count, object
accelerator_list )
Fill in the accelerator_list object (which must be an ObjectList) with count
accelerators starting at start_index.

number GetMenuItems( Display menu_bar, number


start_index, number count, Display menu_list )
Fill in the menu_list object (which must be an ObjectList) with count menus
starting at start_index.

number LockUserInterface( Display menu_bar, number


&lock_token )
Prevent the menu bar from updating until UnlockUserInterface is invoked. This
prevents the menu bar from showing intermediate changes during
reconfigurations.

void RebuildMenuBar( Display menu_bar )


Force a rebuild of the menu bar.

void RemoveAccelerator( Display menu_bar, object


accelerator )
void RemoveMenuBarListener( Display menu_bar,
number listener_id )
void RemoveMenuItem( Display menu_bar, Display
menu_item )
void UnlockUserInterface( Display menu_bar, number
lock_token )
}
The user never creates a menu bar, instead get the application's menu bar by calling
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

194

GetMenuBar().

Menu
Menus are derived from the MenuItem class and can be used wherever menu items
are used.
You can create menus using the following methods:

Display menu = alloc( menu ).init( string name )


Display menu = NewMenu( string name )
The menu object has the following interface:

Display menu : MenuItem


{
object AddMenuItem( Display menu, Display menu_item
)
Add the given menu item to the end of the menu.

object AddMenuItem( Display menu, Display


menu_item, object ref_menu_item )
Add the given menu item before the reference menu item specified by the
ref_menu_item parameter.

object AddSeparator( Display menu )


Add a separator to the end of the menu.

object ClearMenuItems( Display menu )


Clear the menu of all items.

object FindMenuItemByName( Display menu, string


menu_item )
Return the menu item object (if any) with the given name.

number GetMenuItems( Display menu, number


start_index, number count, object item_list )
Fill in the item_list object (which must be an ObjectList) with count menus
starting at start_index.

object ParseMenuPath( Display menu, string


menu_path, number create_intermediate, object
&parent_out, string &name_out )
Return the parent menu and string name of the item given the starting menu
and menu path. It can optionally create all necessary menus in the menu path
if create_intermediate is true.

void RemoveMenuItem( Display menu, Display


menu_item )
Copyright 2012 Gatan Inc. All Rights Reserved.

195

DigitalMicrograph

}
Menu Item
You can create menu items using the following methods:

Display menu_item = alloc( menuItem ).init( string


name )
Display menu_item = NewMenuItem( string name );
A special kind of menu item, called a separator can be created as follows:

object seperator_item = NewMenuSeparator()


The menu item object has the following interface:

Display menuItem
{
object GetAccelerator( Display menu_item )
Return the accelerator (if any) associated with this menu item.

object GetAction( Display menu_item )


Returns the action (if any) associated with this menu item.

number GetIsChecked( Display menu_item )


Returns true or false to indicate whether the menu item is checked or not.

number GetIsEnabled( Display menu_item )


Returns true or false to indicate whether the menu item is enabled or not.

string GetName( Display menu_item )


Returns the name of the menu item.

number IsMenu( Display menu_item )


Returns true or false to indicate whether this menu item is a selectable menu
item or whether it is a menu item representing a sub-menu.

number IsPlaceholder( Display menu_item )


Returns true or false to indicate whether this menu item is a placeholder

number IsSeparator( Display menu_item )


Returns true or false to indicate whether this menu item is a separator or not.

void SetAccelerator( Display menu_item, object


keystroke )
Sets the accelerator associated with this menu item to the accelerator object.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

196

void SetAccelerator( Display menu_item, number


character )
Sets the accelerator associated with this menu item to the given character.

void SetAction( Display menu_item, object action )


Sets the action associated with this menu item to the given action object.
When set this way, the action object must have a DoAction method.

void SetAction( Display menu_item, object handler,


string method_name )
Sets the action associated with this menu item to invoke the given
method_name on the given handler object.

void SetIsChecked( Display menu_item, number


is_checked )
Sets whether the menu item has a check mark next to it or not.

void SetIsEnabled( Display menu_item, number


is_enabled )
Sets whether the menu item is enabled or not.

void SetMnemonic( Display menu_item, number


character )
Sets the mnemonic associated with this menu item.

void SetName( Display menu_item, string name )


Sets the name of the menu item.

}
Action
The action object will be implemented by the user. It should have the following
interface:

interface Action
{
void DoAction( object action )
}
Then use the following function to create the actual action:

Object NewMenuAction( object handler, string


method_name )
Except when creating an accelerator that is attached to the MenuBar it is not
necessary to create an actual object that implements the Action interface. Instead you
can specify a handler object and a method to be invoked on that handler object.

Copyright 2012 Gatan Inc. All Rights Reserved.

197

DigitalMicrograph

Keystroke
Keystrokes should be created using the following function:

Object keyStroke = MakeKeyStroke( string


key_descriptor )
The keystroke object has the following interface:

object Keystroke
{
string DeconstructKeystroke( object keystroke )
Returns the string associated with the keystroke.

string GetKeyDescriptor( object keystroke )


Returns the string associated with the keystroke.

number GetModifiers( object keystroke )


Returns the mask for the modifiers of this keystroke.

}
Accelerator
Accelerators should be created using the following function:

Object accelerator = NewMenuAccelerator( object


keystroke, object action )
The accelerator object has the following interface:

object Accelerator
{
object GetAcceleratorKeystroke( object
accelerator )
Returns the keystroke object associated with this
accelerator.
object GetAcceleratorAction( object accelerator )
Returns the action associated with this accelerator.

number GetIsEnabled( object accelerator )


Returns whether this accelerator is enabled.

void SetIsEnabled( object accelerator, number


is_enabled )
Sets whether this accelerator is enabled.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

198

Key Descriptors
The following keys are defined:

backspace, clear, delete, down, end, enter, esc,


help, home, left, pageup, pagedown, return,
right, space, tab, up
f1, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12
any other single character
In addition, the following modifiers can be prepended to the string:
alt, control, command, menu, shift
Examples are:

control-f4
alt-a
shift-esc
Examples:
Add and remove a global accelerator
When adding a accelerator, or keyboard-short-cut, you should make sure that the
keystroke combo is not used yet elsewhere.

class Custom_Action
{
void DoAction( Object self )
{
Beep()
}
};
// create an object that implements the Action
interface
object handler = alloc( Custom_Action )
// create the action
object action = NewMenuAction( handler, "DoAction" )
// create the accelerator, use the F7 key as the
short-cut
object accelerator = NewMenuAccelerator
( MakeKeyStroke( "f7" ), action )
// get the menuBar and add the accelerator
Display menuBar = GetMenuBar()
Copyright 2012 Gatan Inc. All Rights Reserved.

199

DigitalMicrograph

menuBar.AddAccelerator( accelerator )
After running this script you should here a beep each time you hit the F7 key. To
remove the accelerator run the following script:

// get the menuBar


Display menuBar = GetMenuBar()
// get the list of accelerators added to the menuBar
object accelerator_list = NewObjectList()
number count = menuBar.GetAccelerators( 0, 1000,
accelerator_list )
// look through all the accelerators fo rthe one we
added
number i
for( i = 0; i < count; ++i )
{
object accelerator = accelerator_list.ObjectAt
( i )
object keyStroke = accelerator.
GetAcceleratorKeystroke()
if( keyStroke.GetKeyDescriptor() == "f7" )
{
// remove our accelerator
menuBar.RemoveAccelerator( accelerator )
break;
}
}
Add a menu with various menu items

class Custom_Action
{
void CreateSmallImage( Object self )
{
image img = RealImage("small", 4, 256, 256 )
img = icol
ShowImage( img )
}
void CreateLargeImage( Object self )
{
image img = RealImage("small", 4, 1024,
1024 )
img = irow
ShowImage( img )
}
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

200

};
object handler = alloc( Custom_Action )
object customMenu = newMenu( "Custom" )
object item1 = newMenuItem( "Create small image" )
item1.SetAction( handler, "CreateSmallImage" )
item1.SetMnemonic( 's' ) // make sure to use single
quotes and lower case
item1.SetAccelerator( MakeKeyStroke( "control-3" ) )
item1.SetIsEnabled( 1 )
object item2 = newMenuItem( "Create large image" )
item2.SetAction( handler, "CreateLargeImage" )
item2.SetMnemonic( 'l' ) // make sure to use single
quotes and lower case
item2.SetAccelerator( MakeKeyStroke( "control-4" ) )
item2.SetIsEnabled( 1 )
// get the menuBar
Display menuBar = GetMenuBar()
// add all items together
menuBar.AddMenu( customMenu )
customMenu.AddMenuItem( item1 )
customMenu.AddMenuItem( NewMenuSeparator() )
customMenu.AddMenuItem( item2 )
To remove the menu just added run the following script:

Display menuBar = GetMenuBar()


Display menu = menuBar.FindMenuItemByName( "Custom" )
menuBar.RemoveMenuItem( menu )
1.8.5.5

String Object

String Object
String objects can be easily manipulated in the scripting language. For example the following
script creates a string and prints it to the results window:

String message = "Hello\n"


Result( message )
Concatenating Strings
Strings can be concatenated by using the + symbol, or you can use the function
Copyright 2012 Gatan Inc. All Rights Reserved.

201

DigitalMicrograph

StringAppend() as in the following example:

String message = "Hello"


message += " World"
message.StringAppend( "!\n" )
Result( message )

Comparing Strings
String can be compared using the == operator, the != operator, or using the function
StringCompare(). The == operator returns true if the two string are equal characterby-character, and the != operator returns true if the two strings are not equal
character-by-character.

String message1 = "hello"


String message2 = "hello"
String message3 = "Hello"
if( message1 == message2 )
Result( "Message1 and message2 are identical.
\n")
if( message1 != message3 )
Result( "Message1 and message3 are not
identical.\n")
number compare = message1.StringCompare( message3 )
if( compare > 0 )
Result( "Message1 is \"greater\" than message3.
\n")

Parsing Strings
Strings can be parsed using the functions left(), mid() and right(), as in the following
example:

String
number
number
String
String
String

message = "abcdefghi"
indexD = message.find( "d" )
indexG = message.find( "g" )
abc = message.left( indexD )
def = message.mid( indexD, indexG - indexD )
ghi = message.right( message.len() - indexG )

Result( abc + "\n" )


Result( def + "\n" )
Result( ghi + "\n" )
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

202

The scripting language also provides a means for automatically parsing a string that
contains a number value, as in the following example

String strValue = "23.45"


Number numberValue = strValue.val()
Result( strValue + 10 + "\n")
Result( numberValue + 10 + "\n" )
This script prints out:

23.4510
33.45
because in the first statement strValue is a String and therefore the 10 gets
interpreted as a string and appended. In the second statement numberValue is
a Number, so 10 gets added to it, and the result of the sum is printed.

Methods
String StringAppend( String s1, String s2 )
Appends string s2 to s1, converting its encoding to that of s1 if necessary.

Number StringCompare( String s1, String s2 )


Compares strings 's1' and 's2', returning -1,0, or 1 if s1 is less, equal, or
greater than s2.

Boolean StringIsValid( String str )


Returns true if 'str' is a valid object.

Number len( String str )


Returns the length of a String.

String left( String str, Number count )


Returns leftmost count characters of a string.

String mid( String str, Number offset, Number count )


Returns count characters of a string starting at offset.

String right( String str, Number count )


Returns rightmost count characters of a string.

Number find( String s1, String s2 )


Returns the index of the first occurrence of the substring 's2' in 's1', or '-1' if
there is no such occurrence.

Number val( String str )


Returns the numeric value of a String.

Copyright 2012 Gatan Inc. All Rights Reserved.

203

1.8.5.6

DigitalMicrograph

Document Object Model

Document Object Model


1.8.5.6.1 Window Object

Window Object
DigitalMicrograph displays everything in windows. There are dialog windows, floating
windows, script windows, image windows and the result window. Through the scripting
language you can get information about most of the windows, and control the windows.
First it is important to be able to distinguish between different windows based on their type.
The following types exist:
Description
Application Window
Results Window
Modeless Dialog
Script Window
Image Window

Type
9977
12504
12505
5
4

With the following script you can find all windows that are open within DigitalMicrograph and
check their type:

number i = 0
DocumentWindow window = GetDocumentWindow( i )
while( window.WindowIsValid( ) )
{
Result( i + " : " + window.WindowGetType() + "\n" )
i ++
window = GetDocumentWindow( i )
}
Note that this script does not list the floating windows or the main application window.

Methods
void WindowClose( DocumentWindow window, Boolean
verify )
Closes the wiWindowClosendow, prompting the user if 'verify' is true.

void WindowGetContentBounds( DocumentWindow window,


NumberVariable top, NumberVariable left,
NumberVariable bottom, NumberVariable right )
Gets the bounding rectangle of the content area of the 'window'.
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

204

void WindowGetContentPosition( DocumentWindow window,


NumberVariable x, NumberVariable y )
Gets the position of the top-left corner of the content area of the 'window'.

void WindowGetContentSize( DocumentWindow window,


NumberVariable x, NumberVariable y )
Gets the size of the content area of the 'window'.

void WindowGetFrameBounds( DocumentWindow window,


NumberVariable top, NumberVariable left,
NumberVariable bottom, NumberVariable right )
Gets the bounding rectangle of the frame area of the 'window'.

void WindowGetFramePosition( DocumentWindow window,


NumberVariable x, NumberVariable y )
Gets the position of the top-left corner of the frame area of the 'window'.

void WindowGetFrameSize( DocumentWindow window,


NumberVariable x, NumberVariable y )
Gets the size of the frame area of the 'window'.

void WindowGetMousePosition( DocumentWindow window,


NumberVariable x, NumberVariable y )
Gets the current position of the mouse in the windows coordinate system.

String WindowGetTitle( DocumentWindow window )


Gets the title of the window.

Number WindowGetType( DocumentWindow window )


Gets the type of the window.
void WindowHide( DocumentWindow window )
Hides the window.

Boolean WindowIsOpen( DocumentWindow window )


Returns true if the window has not been closed.

Boolean WindowIsShown( DocumentWindow window )


Returns true if the window is shown.

Boolean WindowIsValid( DocumentWindow window )


Returns true if 'window' points to a valid object.

void WindowSelect( DocumentWindow window )


Brings 'window' to the front.

Copyright 2012 Gatan Inc. All Rights Reserved.

205

DigitalMicrograph

void WindowSendBehind( DocumentWindow window,


DocumentWindow behind_window )
Sends 'window' behind 'behind_window'.

void WindowSetContentBounds( DocumentWindow window,


Number top, Number left, Number bottom, Number
right )
Sets the bounding rectangle of the content area of the 'window'.

void WindowSetContentPosition( DocumentWindow window,


Number x, Number y )
Sets the position of the top-left corner of the content area of the 'window'.

void WindowSetContentSize( DocumentWindow window,


Number x, Number y )
Sets the size of the content area of the 'window'.

void WindowSetFrameBounds( DocumentWindow window,


Number top, Number left, Number bottom, Number
right )
Sets the bounding rectangle of the frame area of the 'window'.

void WindowSetFramePosition( DocumentWindow window,


Number x, Number y )
Sets the position of the top-left corner of the frame area of the 'window'.

void WindowSetFrameSize( DocumentWindow window,


Number x, Number y )
Sets the size of the frame area of the 'window'.

void WindowSetTitle( DocumentWindow window, String


title )
Sets the title of the window.

void WindowShow( DocumentWindow window )


Shows the window.

void WindowUpdate( DocumentWindow window )


Updates 'window's display.

Related Functions
DocumentWindow =( DocumentWindow, ! )
DocumentWindow =( DocumentWindow, DocumentWindow )

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

206

void EditorWindowAddText( DocumentWindow window,


String text )
Appends the text to a editor window.

void EditorWindowGetFont( DocumentWindow window,


String face_name, NumberVariable attributes,
NumberVariable size, NumberVariable
text_encoding )
Gets the font of a script window.

String EditorWindowGetText( DocumentWindow window )


Gets the text in an editor window.

Boolean EditorWindowPrint( DocumentWindow window )


Prints the editor window.

void EditorWindowSaveToFile( DocumentWindow window,


String path )
Saves the editor window to the specified path.

void EditorWindowSetFont( DocumentWindow window,


String face_name, Number attributes, Number
size, Number text_encoding )
Sets the font of a script window.

void EditorWindowSetText( DocumentWindow window,


String text )
Sets the text in an editor window.

DocumentWindow GetApplicationWindow( )
Gets the application window.

DocumentWindow GetDocumentWindow( Number index )


Gets the 'index'th document window.

DocumentWindow GetDocumentWindowByTitle( String


name )
Gets the document window named 'name'.

DocumentWindow GetFloatingWindow( Number index )


Gets the 'index'th floating window.

DocumentWindow GetNthDocumentWindowOfType( Number


type, Number index )
Returns the 'index'th document window of type 'type'.

DocumentWindow GetResultsWindow( Boolean open )


Gets the results window. If the window is not open, and 'open' is true, the
Copyright 2012 Gatan Inc. All Rights Reserved.

207

DigitalMicrograph

results window is opened.

ImageDocument ImageWindowGetImageDocument
( DocumentWindow window )
Gets the image document displayed in the window.

DocumentWindow NewScriptWindow( String title, Number


top, Number left, Number bottom, Number right )
Creates a new editor window.

DocumentWindow NewScriptWindowFromFile( String


file_name, String font_name, Number attributes,
Number size, Number encoding, Number top, Number
left, Number bottom, Number right )
Opens a file into a script window.

DocumentWindow NewScriptWindowFromFile( String


file_name )
Opens a file into a script window.

DocumentWindow NewScriptWindowFromFile( String


file_name, Number top, Number left, Number
bottom, Number right )
Opens a file into a script window.

DocumentWindow NewScriptWindowFromFile( String


file_name, String font_name, Number attributes,
Number size, Number encoding )
Opens a file into a script window.

void ScriptWindowExecute( DocumentWindow window )


Executes the script in the script window.

DocumentWindow WindowNullify( ! )
1.8.5.6.2 Dialogs

Dialogs
DigitalMicrograph has several simple dialogs built-in, such as warning and alert dialogs. See
the table in the reference sections for a list of those. This section describes how to generate
custom dialogs.

Dialog Basics
Creating a custom dialog requires you to describe the dialog using tags. Then you can
use the uiframe class to display the dialog to the user. In the following example a
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

208

simple dialog with one text field is displayed. If the user hits the ok button, the text is
printed to the results window

TagGroup dialog_items
TagGroup dialog_tags = DLGCreateDialog( "Test
Dialog", dialog_items )
TagGroup val_tag = DLGCreateStringField( "" )
dialog_items.DLGAddElement( val_tag )
Object dialog = alloc(uiframe).init(dialog_tags)
if ( dialog.Pose() )
{
Result( val_tag.DLGGetStringValue() + "\n" )
}

In the above example we create a dialog descriptor using the function

TagGroup DLGCreateDialog( String title, TagGroup


dialog_items )
This function also creates the dialogs_items TagGroup. So you need to call
DLGCreateDialog() before you can add the dialog items.
Next we create a string field using the function

TagGroup DLGCreateStringField( String value )


and add the string field to our dialog_items object using

TagGroup DLGAddElement( TagGroup container, TagGroup


element )
Next we create the actual dialog using the 'uiframe' class and finally we call Pose()
using the dialog object which displays the dialog modally, so the user has to click the
OK or Cancel button before they can continue. If the OK button is pressed Pose()
returns true, and the text that the user enters is displayed in the results window.
The interface for the 'uiframe' (user interface frame) class is:

class uiframe : object


{
void Init( object self, TagGroup descriptor )
This function needs to be called in order to initialize the object.

void Pose( object self )


Displays the dialog as a modal Dialog.

void Display( object self, string title )


Copyright 2012 Gatan Inc. All Rights Reserved.

209

DigitalMicrograph

Displays the dialog as a modeless Dialog.

number AboutToCloseDocument( object self, number


verify )
Override this method in order to be notified when the user is about to close a
modeless dialog. This method is not invoked if the dialog is displayed using the
Pose() method.

TagGroup LookupElement( object self, string


identifier )
Retrieves the tagGroup associated with a particular dialog element.

Window GetFrameWindow( object self)


void GetFrameBounds( object self, number &top, number
&left, number &bottom, number &right )
Gets the location of the window. This is useful for positioning other windows
around the dialog. Modal dialogs are displayed in the center of the application
window and modelss dialogs are displayed in the top left hand corner.

Handling messages
If you want to handle messages from, e.g. buttons or pop-up lists, you have to create
your own class that extends uiframe. The following simple example adds a button to
the dialog in the first example, and prints the text in the text field when the user
presses the button.

class testDialog : uiframe


{
void OnButtonPressed( object self )
{
TagGroup val_tag = self.LookUpElement
( "stringValue" )
Result( val_tag.DLGGetStringValue() + "\n" )
}
}
TagGroup dialog_items
TagGroup dialog_tags = DLGCreateDialog( "Test
Dialog", dialog_items )
TagGroup val_tag = DLGCreateStringField( "" ).
DLGIdentifier( "stringValue" )
dialog_items.DLGAddElement( val_tag )

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

210

TagGroup button_tag = DLGCreatePushButton( "Print",


"OnButtonPressed" )
dialog_items.DLGAddElement( button_tag )
Object dialog = alloc( testDialog ).init(dialog_tags)
if ( dialog.Pose() )
{
Result( val_tag.DLGGetStringValue() + "\n" )
}
In this example we first create a class called 'testDialog' that extends 'uiframe'. The
class only adds one function: OnButtonPressed(). In this function we look up the text
field using its identifier, and then print the text to the results window. The rest of the
code is similar to the first example exept:
- we set the identifier of the text field using the function

TagGroup DLGIdentifier( TagGroup element, String id )


This allows us to retreive the text field in the OnButtonPressed() method of the
testDialog class.
- we added a button using the function

TagGroup DLGCreatePushButton( String title, String


action_method )
The action_method argument is set to match the function name in the testDialog
class.
- we allocate testDialog instead of uiframe

Layouts
In the above example the print button appears under the text field. If we want to display
the print button to the right of the text field, we have to explicitly state our layout
requirements when creating the dialog items. To do this you can use the function

TagGroup DLGAddElement( TagGroup container, TagGroup


element, String side )
instead of the one without the side specified. If you would specify "Left" as the side
value for both the text field and the button, then the two items will appear next to one
another.
In more complicated cases you can use a TableLayout as in the following example.

TagGroup dialog_items
Copyright 2012 Gatan Inc. All Rights Reserved.

211

DigitalMicrograph

TagGroup dialog_tags = DLGCreateDialog( "Test


Dialog", dialog_items )
TagGroup address_fields_items
TagGroup address_fields = DLGCreateGroup
( address_fields_items )
DLGLayout( address_fields, DLGCreateTableLayout( 2,
4, 0 ) )
dialog_items.DLGAddElement( address_fields )
address_fields_items.DLGAddElement( DLGCreateLabel
( "Name:" ).DLGAnchor( "East" ) )
address_fields_items.DLGAddElement
( DLGCreateStringField( "" ) )
address_fields_items.DLGAddElement( DLGCreateLabel
( "Address:" ).DLGAnchor( "East" ) )
address_fields_items.DLGAddElement
( DLGCreateStringField( "" ) )
address_fields_items.DLGAddElement( DLGCreateLabel
( "City, State, ZIP:" ).DLGAnchor( "East" ) )
// create three fields for city, state and zip
TagGroup city_fields_items
TagGroup city_fields = DLGCreateGroup
( city_fields_items )
city_fields_items.DLGAddElement( DLGCreateStringField
( "" ), "Left" ).DLGWidth( 22 )
city_fields_items.DLGAddElement( DLGCreateStringField
( "" ), "Left" ).DLGWidth( 4 )
city_fields_items.DLGAddElement( DLGCreateStringField
( "" ), "Left" ).DLGWidth( 10 )
address_fields_items.DLGAddElement( city_fields )
address_fields_items.DLGAddElement( DLGCreateLabel
( "Country:" ).DLGAnchor( "East" ) )
address_fields_items.DLGAddElement
( DLGCreateStringField( "" ) )
Object dialog = alloc( uiframe ).init(dialog_tags)
if ( dialog.Pose() )
{
}
In the above example we create a group that will contain all the elements. We then set
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

212

the layout of the group to be a table layout using the function

TagGroup DLGCreateTableLayout( RealNumber cols,


RealNumber rows, RealNumber uniform )
Uniform indicates if all columns should have the same width.
Next we add a total of 8 items to the address_fileds_items object, one for each cell in
the table. (Note one of the cells contains an other group of 3 items.)
You can see the hierarchical structure of the dialog items by calling

dialog_items.TagGroupOpenBrowserWindow( 0 )
at the end of the previous example.

Floating Windows
In addition to creating modal and modeless dialogs, Floating Windows that can be
docked on the left or right side of the screen can be generated. The procedure is very
similar to creating a standard dialog. The only difference lies in the fact that instead of
calling Pose() or Display() on the uiframe derived object , you use the function

Number RegisterScriptPalette( ScriptObject dialog,


String type, String name )
where dialog is the object derived from 'uiframe', type is unused, and name is the
name that appears in the Floating Windows sub-menu.
The default behavior is for the floating window to be dockable on the left side. If you
want to change that you have to create a TagGroup using the function

TagGroup

DLGBuildPositionFromApplication()

and setting tags in at as in the following example;

class testDialog : uiframe


{
void OnButtonPressed( object self )
{
TagGroup val_tag = self.LookUpElement
( "stringValue" )
Result( val_tag.DLGGetStringValue() + "\n" )
}
}
TagGroup dialog_items

Copyright 2012 Gatan Inc. All Rights Reserved.

213

DigitalMicrograph

TagGroup dialog_tags = DLGCreateDialog( "Test


Dialog", dialog_items )
TagGroup val_tag = DLGCreateStringField( "" ).
DLGIdentifier( "stringValue" )
dialog_items.DLGAddElement( val_tag )
TagGroup button_tag = DLGCreatePushButton( "Print",
"OnButtonPressed" )
dialog_items.DLGAddElement( button_tag )
Object dialog = alloc( testDialog ).init(dialog_tags)
TagGroup position = DLGBuildPositionFromApplication()
position.TagGroupSetTagAsString( "Width", "Medium" )
DLGSide( position, "Right" )
DLGPosition( dialog_tags, position )
RegisterScriptPalette( dialog, "Test", "Test
Window" )

Methods
Index to methods:

Dialog Attribute Access Functions


Set Property Values
Get Property Values
Dialog Contruction Functions
Modeless Positioning Utilities
Bitmap Functions for Bevel Buttons
Label Functions
Button Functions
Group Functions
Field Functions
Checkbox Functions
Box Functions
Radio Button Functions
List Functions
Pop-up Menu Functions
Choice-item Functions
Panel Functions
Tab Functions
Textbox Functions
Image Pop-up Functions
Progress Bar Functions
Graphic Functions
DIALOG ATTRIBUTE ACCESS FUNCTIONS
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

214

Set Property Values


TagGroup DLGSide( TagGroup element, String side )
Sets the 'Side' attribute: "Left", "Right", "Top", "Bottom", "Center"; returns the
element.

TagGroup DLGAnchor( TagGroup element, String anchor )


Sets the 'Anchor' attribute: "North", "South", "East", "West"; returns the
element.

TagGroup DLGFill( TagGroup element, String fill )


Sets the 'Fill' attribute: "X", "Y", "XY", "Both"; returns the element.

TagGroup DLGExpand( TagGroup element, Number


do_expand )
Sets the 'Expand' attribute: 0 for x-direction, 1 for y-direction; returns the
element.

TagGroup DLGExpand( TagGroup element, String s )


Sets the 'Expand' attribute: "X", "Y", "XY"; returns the element.

TagGroup DLGInternalPadding( TagGroup element, number


x_pad, number y_pad )
Sets the 'InternalPadding' attribute; returns the element.

TagGroup DLGInternalPadding( TagGroup element, Number


t_pad, Number l_pad, Number b_pad, Number
r_pad )
Sets the 'InternalPadding' attribute; returns the element.

TagGroup DLGExternalPadding( TagGroup element, Number


x_pad, Number y_pad )
Sets the 'ExternalPadding' attribute; returns the element.

TagGroup DLGExternalPadding( TagGroup element, Number


t_pad, Number l_pad, Number b_pad, Number
r_pad )
Sets the 'ExternalPadding' attribute; returns the element.

TagGroup DLGValue( TagGroup element, Number value )


Sets the numeric 'Value' attribute; returns the element.

TagGroup DLGValue( TagGroup element, string value )


Sets the string 'Value' attribute; returns the element.

TagGroup DLGValue( object frame, string identifier,


number val )
Copyright 2012 Gatan Inc. All Rights Reserved.

215

DigitalMicrograph

Sets the numeric 'Value' attribute in a labeled element in a uiframe object;


returns the TagGroup containing the identifier.

TagGroup DLGValue( object frame, string identifier,


string val )
Sets the string 'Value' attribute in a labeled element in a uiframe object; returns
the TagGroup containing the identifier.

TagGroup DLGMinValue( TagGroup element, Number


value )
Sets the 'MinValue' attribute; returns the element.

TagGroup DLGMaxValue( TagGroup element, Number


value )
Sets the 'MaxValue' attribute; returns the element.

TagGroup DLGIdentifier( TagGroup element, String id )


Sets the 'Identifier' attribute; returns the element.

TagGroup DLGWidth( TagGroup element, number width )


Sets the 'Width' attribute; returns the element.

TagGroup DLGHeight( TagGroup element, number height )


Sets the 'Height' attribute; returns the element.

TagGroup DLGFont( TagGroup element, string font )


Sets the 'Font' attribute; returns the element.

TagGroup DLGTitle( TagGroup element, string title )


Sets the 'Title' attribute; returns the element.

TagGroup DLGActionMethod( TagGroup element, string


action_method )
Sets the 'ActionMethod' attribute; returns the element.

TagGroup DLGChangedMethod( TagGroup element, string


changed_method )
Sets the 'ChangedMethod' attribute; returns the element.

TagGroup DLGMultipleSelect( TagGroup tg, number


multiple_select )
Sets the 'MultipleSelect' attribute for Lists; returns the element.

TagGroup DLGLayout( TagGroup tg, TagGroup layout )


Sets the 'Layout' attribute for Groups; returns the element.

TagGroup DLGEnabled( TagGroup item, number enabled )


Sets the 'enabled' attribute of a an item.
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

216

TagGroup DLGBitmapData( TagGroup tg, Image img )


Sets the image data for a bitmap

TagGroup DLGInvalid( TagGroup tg, number isInvalid )


Sets the 'Invalid' attribute for a modified element. Used for run-time update of
dialog displays,

TagGroup DLGLabel( TagGroup tg, string label )


Sets the 'Label' attribute for an element

Get Property Values


number DLGGetValue( TagGroup tags, number &value )
Gets the numeric 'Value' attribute setting; returns 1 if succeeded, 0 otherwise.

number DLGGetValue( TagGroup tags, string &value )


Gets the string 'Value' attribute setting; returns 1 if succeeded, 0 otherwise.

number DLGGetValue( object frame, string identifier,


number &val )
Gets the numeric 'Value' attribute setting for a labeled element in a uiframe
object; returns 1 if succeeded, 0 otherwise.

number DLGGetValue( object frame, string identifier,


string &val )
Gets the string 'Value' attribute setting for a labeled element identifier in a
uiframe object; returns 1 if succeeded, 0 otherwise.

number DLGGetValue( TagGroup tags )


Returns the numeric 'Value' attribute setting.

string DLGGetStringValue( TagGroup tags )


Returns the string 'Value' attribute setting.

TagGroup DLGGetItems( TagGroup tags )


Returns the TagGroup in the 'Items' attribute of an element.

number DLGGetIdentifier( TagGroup tags, string


&identifier )
Returns the string in the 'Identifier' attribute of an element.

number DLGGetNthLabel( TagGroup tags, number index,


string &label_str )
Gets the label of the nth item in the 'Items' TagGroup of an element; returns 1
if succeeded, 0 otherwise.

Copyright 2012 Gatan Inc. All Rights Reserved.

217

DigitalMicrograph

number DLGGetLabelIndex( TagGroup tags, string title,


number &index )
Gets the index of the item of a given title in the 'Items' TagGroup of an element;
returns 1 if succeeded, 0 otherwise.

string DLGGetType( TagGroup tags )


Gets the type attribute of an element.

number DLGGetWidth( TagGroup tags )


Gets the width of an element

number DLGGetHeight( TagGroup tags )


Gets the height of an element

Image DLGGetBitmapData( TagGroup bitmap )


Gets the RGB image stored in a bitmap

String DLGGetLabel( TagGroup element )


Gets the label of an element

String DLGGetTitle( TagGroup element )


Gets the label of an element (dialog or label)

DIALOG CONSTRUCTION FUNCTIONS


TagGroup DLGCreateElement( string type )
Create a dialog element of the specified type; returns the newly created
element.

TagGroup DLGCreateElementWithItems( string type,


TagGroup &items )
Create a container of the specified type, and passes back an empty items list;
returns the container.

TagGroup DLGCreateElementWithItems( string type)


Create a container of the specified type

TagGroup DLGAddElement( TagGroup container, TagGroup


element )
Add an element to a container or element list; returns the element.

TagGroup DLGAddElement( TagGroup container, TagGroup


element, String side )
Add an element with the specified 'Side' attribute to a container or element list;
returns the element.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

218

TagGroup DLGAddElement( TagGroup container, TagGroup


element, String side, String anchor )
Add an element with the specified 'Side' and 'Anchor' attributes to a container
or element list; returns the element.

TagGroup DLGAddElementBefore( TagGroup container,


number index, TagGroup element )
Insert an element before the given index; returns the element

TagGroup DLGAddElementAfter( TagGroup container,


number index, TagGroup element )
Insert an element after the given index; returns the element

TagGroup DLGGetElement( TagGroup container, number


index )
Retrieve an element at the given index from a container.

TagGroup DLGGetElement( TagGroup container, string


label, number &index )
Retrieve an element with the given label; passes back the index of the
element

TagGroup DLGGetElement( TagGroup container, string


label )
Retrieve an element with the given label

TagGroup DLGRemoveElement( TagGroup container, number


index )
Remove an element at the given index from a container; returns the removed
element.

TagGroup DLGRemoveLastElement( TagGroup container)


Remove the last element from a container; returns the removed element.

TagGroup DLGRemoveElement( TagGroup container, string


label )
Remove an element with the given label; returns the removed element.

Number DLGSetElement( TagGroup container, number


index, TagGroup new_element )
Sets the element at the given index; returns 1 if succeeded, 0 otherwise

Number DLGSetElement( TagGroup container, string


label, TagGroup new_element )
Sets the element with the given label; returns 1 if succeeded, 0 otherwise

TagGroup DLGSetElementLabel( TagGroup container,


number index, string new_label )
Copyright 2012 Gatan Inc. All Rights Reserved.

219

DigitalMicrograph

Sets the label of the element at the given index; returns the element

TagGroup DLGSetElementLabel( TagGroup container,


string label, string new_label )
Sets the label of the element with the given label; returns the element

TagGroup DLGCreateDialog( string title, TagGroup


&dialog_items )
Create a dialog container with the given title; passes back an empty items list,
and returns the dialog container.

TagGroup DLGCreateDialog( string title )


Create a dialog container with the given title

TagGroup DLGCreateTableLayout( number cols, number


rows, number uniform )
Create a table layout with the given number of columns, rows, and whether the
table cells are uniform in size; returns the table layout.

TagGroup DLGCreateTableLayout( number cols, number


rows, string uniform )
Create a table layout with the given number of columns, rows, and whether the
table cells are uniform in size; returns the table layout.

TagGroup DLGTableLayout( TagGroup element, number


columns, number rows, number uniform )
Sets the 'Layout' attribute to a table layout with the given number of columns,
rows, and cell uniformity flag; returns the element.

TagGroup DLGTableLayout( TagGroup tg, number columns,


number rows, string uniform_str )
Sets the 'Layout' attribute to a table layout with the given number of columns,
rows, and cell uniformity flag; returns the element.

Modeless Positioning Utilities


TagGroup DLGBuildPositionFromApplication()
Creates a dialog position descriptor that uses the bounds of the largest
document window as reference; returns the position descriptor.

TagGroup DLGBuildPositionFromWindow( DocumentWindow


wnd )
Creates a dialog position descriptor that uses the bounds of the given window
as reference; returns the position descriptor.

TagGroup DLGBuildPositionFromUIFrame( object frame )


Creates a dialog position descriptor that uses the bounds of the UI frame as
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

220

reference; returns the position descriptor.

TagGroup DLGBuildAutoSize()
Creates an auto-size position descriptor; returns the descriptor.

TagGroup DLGBuildMatchSize()
Creates a match-size position descriptor; returns the descriptor.

TagGroup DLGBuildAbsoluteSize( number inches )


Creates an absolute-size position descriptor; returns the descriptor.

TagGroup DLGBuildRelativePosition( string sense,


number rel )
Creates a relative-size position descriptor; sense: "Inside", "Outside"; rel: 0, 1;
returns the descriptor.

TagGroup DLGBuildPosition( number top, number left,


number bottom, number right )
Creates a dialog position descriptor with the given reference bounds; returns
the position descriptor.

TagGroup DLGPosition( TagGroup tags, TagGroup


position )
Sets the 'Positioning' attribute of a dialog to the given position descriptor;
returns the dialog.

TagGroup DLGPosition( TagGroup tags, number top,


number left, number bottom, number right )
Creates a dialog position descriptor with the given reference bounds, and adds
it to the given dialog tags; returns the dialog tags.

BITMAP FUNCTIONS FOR BEVEL BUTTONS


TagGroup DLGCreateBitmap( Image img )
Creates a bitmap TagGroup from the given image.

LABEL FUNCTIONS
TagGroup DLGCreateLabel( String label_string )
Creates a label with the given text.

TagGroup DLGCreateLabel( string label_string, number


width )
Creates a label with the given text and maximum number of characters.

Copyright 2012 Gatan Inc. All Rights Reserved.

221

DigitalMicrograph

BUTTON FUNCTIONS
TagGroup DLGCreatePushButton( String title, String
action_method )
Creates a single-state text button with the given display title and action
method.

TagGroup DLGCreateBevelButton( TagGroup onBitmap,


TagGroup offBitmap, string actionmethod )
Creates a single-state bitmap button with the given on/off bitmap TagGroups
and action method.

TagGroup DLGCreateBevelButton( Image onImage, Image


offImage, string actionmethod )
Creates a single-state bitmap button with the given on/off images and action
method.

TagGroup DLGCreateBevelButton( Image img, string


actionmethod )
Creates a single-state bitmap button with the given image and action method.

TagGroup DLGCreateDualStateBevelButton( string


identifier, TagGroup onBitmap, TagGroup
offBitmap, string actionmethod )
Creates a dual-state bitmap button with the given identifier, on/off bitmap
TagGroups, and action method.

TagGroup DLGCreateDualStateBevelButton( string


identifier, Image onImage, Image offImage,
string actionmethod )
Creates a dual-state bitmap button with the given identifier, on/off images, and
action method.

TagGroup DLGCreateDualStateBevelButton( string


identifier, Image img, string actionmethod )
Creates a dual-state bitmap button with the given identifier, image, and action
method.

Number DLGGetBevelButtonOn( object frame, String


identifier, TagGroup &tags )
Gets the On/Off state of a labeled bevel button in a uiframe object; passes
back the button TagGroup in tags, and 1 if on , 0 if off.

TagGroup DLGBevelButtonOn( TagGroup button_tags,


number isOn )
Sets the On/Off state of a button; returns the button TagGroup.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

222

TagGroup DLGBevelButtonOn( object frame, string


identifier, number isOn )
Sets the On/Off state of a labeled button in a uiframe object; returns the button
TagGroup.

GROUP FUNCTIONS
TagGroup DLGCreateGroup()
Creates a group container

TagGroup DLGCreateGroup( TagGroup &items )


Creates a group container; passes back an empty items list, and returns the
container.

TagGroup DLGGroupItems( TagGroup item1, TagGroup


item2 )
Creates a group containing the given two items; returns the container.

TagGroup DLGGroupItems( TagGroup item1, TagGroup


item2, TagGroup item3 )
Creates a group containing the given three items; returns the container.

TagGroup DLGGroupItems( TagGroup item1, TagGroup


item2, TagGroup item3, TagGroup item4 )
Creates a group containing the given four items; returns the container.

FIELD FUNCTIONS
TagGroup DLGCreateRealField( number value )
Creates a real-valued field with the given initial value, field width, and format.

TagGroup DLGCreateRealField( number value, number


width, number format )
Creates a real-valued field with the given initial value, field width, and format.

TagGroup DLGCreateRealField( number value, number


width, number format, string changedmethod )
Creates a real-valued field with the given initial value, field width, format, and
changed method.

TagGroup DLGCreateRealField( string title, TagGroup


&field_item, number value, number width, number
format )
Creates a named real-valued field group with the given title, initial value, width
and format; passes back the field item; returns the named field group.

Copyright 2012 Gatan Inc. All Rights Reserved.

223

DigitalMicrograph

TagGroup DLGCreateIntegerField( number value )


Creates a integer-valued field with the given initial value, and field width.

TagGroup DLGCreateIntegerField( number value, number


width )
Creates a integer-valued field with the given initial value, and field width.

TagGroup DLGCreateIntegerField( number value, number


width, string changedmethod )
Creates a integer-valued field with the given initial value, field width, and
changed method.

TagGroup DLGCreateIntegerField( string title,


TagGroup &field_item, number value, number width
)
Creates a named integer-valued field group with the given title, initial value and
width; passes back the field item; returns the named field group.

TagGroup DLGCreateStringField( String value )


Creates a string-valued field with the given initial value, and field width.

TagGroup DLGCreateStringField( String value, number


width )
Creates a string-valued field with the given initial value, and field width.

TagGroup DLGCreateStringField( String value, number


width, string changedmethod )
Creates a string-valued field with the given initial value, field width, and
changed method.

TagGroup DLGCreateStringField( string title, TagGroup


&field_item, string value, number width )
Creates a named string-valued field group with the given title, initial value and
width; passes back the field item; returns the named field group.

CHECKBOX FUNCTIONS
TagGroup DLGCreateCheckBox( string title )
Creates a checkbox with the given text.

TagGroup DLGCreateCheckBox( string title, number


state )
Creates a checkbox with the given text and initial checked/unchecked state

TagGroup DLGCreateCheckBox( string title, number


state, string changedmethod )
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

224

Creates a checkbox with the given text, initial checked/unchecked state, and
changed method.

BOX FUNCTIONS
TagGroup DLGCreateBox()
Creates a box container

TagGroup DLGCreateBox( String title)


Creates a box with the given title

TagGroup DLGCreateBox( TagGroup &items )


Creates a box container; passes back an empty items list, and returns the
container.

TagGroup DLGCreateBox( String title, TagGroup


&items )
Creates a box with the given title; passes back an empty items list, and
returns the container.

RADIO BUTTON FUNCTIONS


TagGroup DLGCreateRadioList( )
Creates a radio button list container

TagGroup DLGCreateRadioList( number value )


Creates a radio button list container with the given initial value

TagGroup DLGCreateRadioList( number value, string


changedmethod )
Creates a radio button list container with the given initial value and changed
method;

TagGroup DLGCreateRadioList( TagGroup &items )


Creates a radio button list container; passes back an empty items list, and
returns the container.

TagGroup DLGCreateRadioList( TagGroup &items, number


value )
Creates a radio button list container with the given initial value; passes back an
empty items list, and returns the container.

TagGroup DLGCreateRadioList( TagGroup &items, number


value, string changedmethod )
Creates a radio button list container with the given initial value and changed
method; passes back an empty items list, and returns the container.
Copyright 2012 Gatan Inc. All Rights Reserved.

225

DigitalMicrograph

TagGroup DLGCreateRadioItem( string label, number


value )
Createsa radio button item with the given title and value

TagGroup DLGAddRadioItem( TagGroup rad_container,


string label, number value )
Creates and adds a radio button item with the given title and value to a radio
button list; returns the radio button item.

LIST FUNCTIONS
TagGroup DLGCreateList( number width, number height )
Creates a list container with the given width and height

TagGroup DLGCreateList( string changedmethod, number


width, number height )
Creates a list container with the given width, height, and changed method;

TagGroup DLGCreateList( string changedmethod, string


actionmethod, number width, number height )
Creates a list container with the given width, height, changed method and
action method;

TagGroup DLGCreateList( TagGroup &items, number


width, number height )
Creates a list container with the given width and height; passes back an empty
items list, and returns the container.

TagGroup DLGCreateList( TagGroup &items, string


changedmethod, number width, number height )
Creates a list container with the given width, height, and changed method;
passes back an empty items list, and returns the container.

TagGroup DLGCreateList( TagGroup &items, string


changedmethod, string actionmethod, number
width, number height )
Creates a list container with the given width, height, changed method and
action method; passes back an empty items list, and returns the container.

TagGroup DLGCreateListItem( string label, number


selected )
Creates a list item with the given label.

TagGroup DLGAddListItem( TagGroup item_container,


string label, number selected )
Adds a list item with the given label to a list.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

226

POPUP MENU FUNCTIONS


TagGroup DLGCreatePopup( )
Creates a popup menu

TagGroup DLGCreatePopup( number value )


Creates a popup menu with the given initial value

TagGroup DLGCreatePopup( number value, string


changedmethod )
Creates a popup menu with the given initial value and changed method

TagGroup DLGCreatePopup( TagGroup &items )


Creates a popup menu; passes back an empty items list, and returns the
container..

TagGroup DLGCreatePopup( TagGroup &items, number


value )
Creates a popup menu with the given initial valuepasses back an empty items
list, and returns the container.

TagGroup DLGCreatePopup( TagGroup &items, number


value, string changedmethod )
Creates a popup menu with the given initial value and changed method;
passes back an empty items list, and returns the container.

TagGroup DLGCreatePopup( string title, TagGroup


&label_item, TagGroup &popup_item, TagGroup
&choice_items, number value )
Creates a named popup menu group with the given title and initial value;
passes back the label for the popup title, the popup menu, and an empty
popup items list; returns the named popup group.

TagGroup DLGCreateBoxedPopup( string boxTitle,


TagGroup &popup_item, TagGroup &choice_items,
number value )
Creates a named box containing a popup menu with the given title and initial
value; passes back the popup menu and an empty popup items list; returns
the box element.

TagGroup DLGCreatePopupItemEntry( string label )


Creates a popup entry with the given label.

TagGroup DLGAddPopupItemEntry( TagGroup container,


string label )
Adds a popup entry with the given label to a list of popup items; returns the
popup entry.
Copyright 2012 Gatan Inc. All Rights Reserved.

227

DigitalMicrograph

TagGroup DLGAddPopupItemEntry( TagGroup items, string


label, number enabled )
Adds a popup entry with the given label to a list of
popup items; returns the popup entry.
void DLGSetNthChoice( TagGroup tags, number index,
string title, number enabled )
Sets the nth choice in a choice list. Also invalidates the choice item.

CHOICE ITEM FUNCTIONS


TagGroup DLGCreateChoice( )
Creates a choice item

TagGroup DLGCreateChoice( number value )


Creates a choice item with the given initial value

TagGroup DLGCreateChoice( number value, string


changedmethod )
Creates a choice item with the given initial value and changed method

TagGroup DLGCreateChoice( TagGroup &items )


Creates a choice item; passes back an empty items list, and returns the
container..

TagGroup DLGCreateChoice( TagGroup &items, number


value )
Creates a choice item with the given initial value; passes back an empty items
list, and returns the container.

TagGroup DLGCreateChoice( TagGroup &items, number


value, string changedmethod )
Creates a choice item with the given initial value and changed method; passes
back an empty items list, and returns the container.

TagGroup DLGCreateChoice( string title, TagGroup


&label_item, TagGroup &choice_item, TagGroup
&choice_items, number value )
Creates a named choice item group with the given title and initial value;
passes back the label for the choice title, the choice item, and an empty
choice items list; returns the named choice group.

TagGroup DLGCreateBoxedChoice( string boxTitle,


TagGroup &choice_item, TagGroup &choice_items,
number value )
Creates a named box containing a choice item with the given title and initial
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

228

value; passes back the choice item and an empty choice items list; returns the
box element.

TagGroup DLGCreateChoiceItemEntry( string label )


Creates a choice entry with the given label

TagGroup DLGAddChoiceItemEntry( TagGroup container,


string label )
Adds a choice entry with the given label to a list of choice items; returns the
choice entry.

PANEL FUNCTIONS
TagGroup DLGCreatePanelList( )
Creates a panel list container

TagGroup DLGCreatePanelList( number value )


Creates a panel list container with the given initially selected panel index;

TagGroup DLGCreatePanelList( TagGroup &items )


Creates a panel list container; passes back an empty panel list, and returns
the container.

TagGroup DLGCreatePanelList( TagGroup &items, number


value )
Creates a panel list container with the given initially selected panel index;
passes back an empty panel list, and returns the container.

TagGroup DLGCreatePanel( )
Creates a panel element

TagGroup DLGCreatePanel( TagGroup &items )


Creates a panel element; passes back an empty items list, and returns the
element.

TagGroup DLGAddPanel( TagGroup container, TagGroup


panel )
Adds a panel element to a panel list; returns the panel element.

TagGroup DLGAddPanel( TagGroup container)


Creates and adds a panel element to a panel list; returns an empty items list
for the new panel.

TAB FUNCTIONS
TagGroup DLGCreateTabList( )
Copyright 2012 Gatan Inc. All Rights Reserved.

229

DigitalMicrograph

Creates a tab list container

TagGroup DLGCreateTabList( number value )


Creates a tab list container with the given initially selected tab index

TagGroup DLGCreateTabList( number value, string


changedmethod )
Creates a tab list container with the given initially selected tab index and
changed method

TagGroup DLGCreateTabList( TagGroup &items )


Creates a tab list container; passes back an empty tab list, and returns the
container.

TagGroup DLGCreateTabList( TagGroup &items, number


value )
Creates a tab list container with the given initially selected tab index; passes
back an empty tab list, and returns the container.

TagGroup DLGCreateTabList( TagGroup &items, number


value, string changedmethod )
Creates a tab list container with the given initially selected tab index and
changed method; passes back an empty tab list, and returns the container.

TagGroup DLGCreateTab( string label )


Creates a tab with the given label

TagGroup DLGCreateTab( TagGroup &tab_items, string


label )
Creates a tab with the given label; passes back an empty panel items list and
returns the tab element.

TagGroup DLGAddTab( TagGroup container, string


label )
Creates and adds a tab with the given label to a tab list; returns an empty
items list for the new tab.

TagGroup DLGAddTab( TagGroup container, TagGroup


tab )
Adds a tab to a tab list; returns the tab element.

TEXT BOX FUNCTIONS


TagGroup DLGCreateTextBox( number width, number
height, number length )
Creates a text box with the given width, height, and text length.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

230

IMAGE POPUP FUNCTIONS


TagGroup DLGCreateImagePopup()
Creates a popup menu listing the currently open images.

TagGroup DLGCreateImagePopup( number image_id )


Creates a popup menu listing the currently open images, with the name of the
image with the given image ID initially selected.

PROGRESS BAR FUNCTIONS


TagGroup DLGCreateProgressBar()
Creates a progress bar.

TagGroup DLGCreateProgressBar( string identifier )


Creates a progress bar.

TagGroup DLGSetProgress( object frame, string


identifier, number percentage_complete )
Sets the progress status of a progress bar in a uiframe object; returns the
TagGroup containing the identifier.

TagGroup DLGGetProgress( object frame, string


identifier, number &percentage_complete )
Gets the progress status of a progress bar in a uiframe object; returns the
TagGroup containing the identifier.

GRAPHIC FUNCTIONS
TagGroup DLGCreateGraphic( number width, number
height )
Creates a graphic element with the given width and height

TagGroup DLGAddBitmap(TagGroup graphic, TagGroup


bitmap_item )
Adds a bitmap to a graphic element

TagGroup DLGAddBitmap( TagGroup graphic, Image img )


Creates a bitmap from the given image and adds it to the graphic element

TagGroup DLGCreateStandardBevelButton( Image img )


Creates a standard bevel button item.

Copyright 2012 Gatan Inc. All Rights Reserved.

231

DigitalMicrograph

TagGroup DLGCreateStandardBevelButton( Image img,


number onOff )
Creates a standard bevel button with the given image and sets it value to
onOff.
1.8.5.6.3 ImageDocument Object

ImageDocument Object
Overview
Image documents are the base containers for image displays and other components.
A simple example that shows how to create an ImageDocument and then add images
follows

// create the ImageDocument


ImageDocument imageDoc = CreateImageDocument( "New
ImageDocument" )
// ImageDocumentEnsurePlacedOnPage() is called so
that the imageDocument
// has coordinates. The results you get depend on
your printer setup.
imageDoc.ImageDocumentEnsurePlacedOnPage()
number top, left, bottom, right
imageDoc.ImageDocumentGetPageBounds( top, left,
bottom, right )
Result( top + " " + left + " " + bottom + " " +
right + "\n" )
// calculate the pageHeight and pageWidth
number pageHeight = bottom - top
number pageWidth = right - left
// create a float image of 256 by 256
number width = 256, height = 256
Image img := RealImage("dummy", 4, width, height )
img = irow
// add the new image to the imageDocument
imageDoc.ImageDocumentAddImage( img )
// create a second float image
Image img2 := RealImage("dummy2", 4, width, height
)
img2 = icol
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

232

// add this image to the imageDocument as well


imageDoc.ImageDocumentAddImage( img2 )
// get the display object of the first image
ImageDisplay imgDisplay = img.ImageGetImageDisplay
(0 )
// place it centered at the top
top = 0
left = (pageWidth - width ) /2
bottom = height
right = (pageWidth + width) /2
imgDisplay.ComponentSetRect( top, left, bottom,
right )
// get the display object of the second image
ImageDisplay img2Display = img2.
ImageGetImageDisplay(0 )
// place it centered at the bottom
top = pageHeight - height
left = (pageWidth - width ) /2
bottom = pageHeight
right = (pageWidth + width) /2
img2Display.ComponentSetRect( top, left, bottom,
right )
// put imageDocument in page mode and show it
imageDoc.ImageDocumentSwitchToPageMode()
imageDoc.ImageDocumentShow()
Note that when running the above script, the imageDocument has the title "dummy"
eventhough the title was set to "New ImageDocument". If we left the imageDocument
empty and then displayed it, the title would have been "New ImageDocument".
Also note that we first had to call ImageDocumentEnsurePlacedOnPage() to make
sure that coordinates would be available. The coordinate system used here is called
"page coordinates". When we place the imageDisplays they are located with respect
to the dotted line on the page. We can change the size of the page by changing the
margins in the page set-up.
Each image document has a root component that can be accessed via
ImageDocumentGetRootComponent, in which other components may be placed. In
the following example this is used to add a new text annotation.

ImageDocument imageDoc = CreateImageDocument( "New


ImageDocument" )
Copyright 2012 Gatan Inc. All Rights Reserved.

233

DigitalMicrograph

imageDoc.ImageDocumentEnsurePlacedOnPage()
number top, left, bottom, right
imageDoc.ImageDocumentGetPageBounds( top, left,
bottom, right )
number pageHeight = bottom - top
Component comp = imageDoc.
ImageDocumentGetRootComponent()
Component textAnnot = NewTextAnnotation( 0,
pageHeight/2, "Text Annotation", 12 )
comp.ComponentAddChildAtEnd( textAnnot )
imageDoc.ImageDocumentSwitchToPageMode()
imageDoc.ImageDocumentShow()

Coordinate Systems
An image document may be viewed in its entirety in page mode, or one of its top-level
image displays may be viewed in image mode.
The coordinate system used to express the portion of the document currently viewed
in the window is view coordinates. In page mode this is equivalent to page
coordinates, as in the above script examples; in image mode it has no equivalent, but
methods like ComponentGetBoundingRectInView can be used to interpret the
coordinates in terms of the visible components. View coordinates can be related to
window coordinates by finding the currently visible area in view coordinates using
ImageDocumentGetVisibleViewRect, and then by finding the visible area in screen
coordinates using ImageDocumentGetWindow to get the document's window and
WindowGetContentBounds to get the size of the interior of the window. See the
following script for an example:

// create the ImageDocument


ImageDocument imageDoc = CreateImageDocument( "New
ImageDocument" )
imageDoc.ImageDocumentEnsurePlacedOnPage()
number top, left, bottom, right
imageDoc.ImageDocumentGetPageBounds( top, left,
bottom, right )
number pageHeight = bottom - top
number pageWidth = right - left
// create image, add to ImageDocument
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

234

number width = 256, height = 256


Image img := RealImage("dummy", 4, width, height )
img = irow
imageDoc.ImageDocumentAddImage( img )
ImageDisplay imgDisplay = img.ImageGetImageDisplay
(0 )
top = 0
left = (pageWidth - width ) /2
bottom = height
right = (pageWidth + width) /2
imgDisplay.ComponentSetRect( top, left, bottom,
right )
// try running this script with and without the
following line
imageDoc.ImageDocumentSwitchToPageMode()
imgDisplay.ComponentGetBoundingRectInView(top,
left, bottom, right )
Result( "ImageDisplay Rect in View: " + top + "
+ left + " " + bottom + " " + right +
"\n" )

"

// first show before getting all the window


locations
imageDoc.ImageDocumentShow()
// get locations
imageDoc.ImageDocumentGetVisibleViewRect(top,
left, bottom, right )
Result( "ImageDocument Visible Rect: " + top + "
" + left + " " + bottom + " " + right +
"\n" )
// get interior of window, this correponds in size
to ImageDocument
DocumentWindow wind = imageDoc.
ImageDocumentGetWindow()
wind.WindowGetContentBounds( top, left, bottom,
right )
Result( "Window Content Bounds: " + top + " " +
left + " " + bottom + " " + right + "\n" )
// get exterior of window
wind.WindowGetFrameSize( width, height )

Copyright 2012 Gatan Inc. All Rights Reserved.

235

DigitalMicrograph

Result( "Window frame size: " + width + "


height + "\n" )

" +

wind.WindowGetFramePosition( top, left )


Result( "Window frame position: " + top + "
left + "\n" )

" +

Reference Points
Each image document mode has a reference point size, which is the height of one
text point, and a minimum resolution, which is the size of a pixel in the appropriate
drawing surface. The reference point size in view coordinates is given by
ImageDocumentGetReferencePointSize, and the minimum point size in view
coordinates by ImageDocumentGetMinimumPointSize. In image mode, both the
reference point and the minimum point are one screen pixel. In page mode, the
reference point size is the size of a dot at 72dpi ( before any scaling specified in the
print dialog ), and the minimum point size is the dot size of the selected printer.

Methods
void ImageDocumentAddImage( ImageDocument imgDoc,
ImageReference image )
Adds the given image to the list maintained in the image document.

ImageDisplay ImageDocumentAddImageDisplay
( ImageDocument imgDoc, ImageReference image,
Number displayType )
Adds the given image and an image display for it of the given type.

void ImageDocumentAddToUserInterface( ImageDocument


imgDoc )
Places the image document in the list of user interface documents.

void ImageDocumentClean( ImageDocument imgDoc )


Marks the image document as clean (doesn't need to be saved).

ImageDocument ImageDocumentClone( ImageDocument


imgDoc, Boolean doDeepCopy )
Returns a duplicate of the image docuemnt, creating a copy of its images if
'doDeepCopy' is true.

void ImageDocumentClose( ImageDocument imgDoc,


Boolean saving )
Closes the given image document. If saving is true then asks whether to save
it, otherwise just closes it.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

236

Number ImageDocumentCountImages( ImageDocument imgDoc


)
Returns the number of images contained in this image document.

ImageReference
ImageDocumentCreateRGBImageFromDocument
( ImageDocument imgDoc, Number width, Number
height, Number extract_style, Number constraints
)
Creates an image by scaling the image document into ( width, height ).

void ImageDocumentDeleteImage( ImageDocument imgDoc,


ImageReference image )
Deletes the given image from this image document.

Boolean ImageDocumentDoesImageWithIDExist
( ImageDocument imgDoc, Number id )
Determines whether the image with the given id exists within this image
document.

void ImageDocumentEnsurePlacedOnPage( ImageDocument


imgDoc )
Makes sure the document has been layed out on the physical page.

Number ImageDocumentGetAsPICT( ImageDocument


imgDoc )
Returns this image as a PICT.

Component ImageDocumentGetComponentByID
( ImageDocument imgDoc, Number id )
Returns an annotation contained in this image document by id.

Number ImageDocumentGetID( ImageDocument imgDoc )


Gets the id of the image document.

ImageReference ImageDocumentGetImage( ImageDocument


imgDoc, Number position )
Returns the image contained within this image document by position.

ImageReference ImageDocumentGetImageByID
( ImageDocument imgDoc, Number id )
Returns an image contained in this image document by id.

ImageDisplay ImageDocumentGetImageModeDisplay
( ImageDocument imgDoc )
Gets the image display targeted by the current image mode.

Copyright 2012 Gatan Inc. All Rights Reserved.

237

DigitalMicrograph

void ImageDocumentGetMinimumPointSize( ImageDocument


imgDoc, NumberVariable x, NumberVariable y )
Gets the size of the minimum point in view coordinates.

String ImageDocumentGetName( ImageDocument imgDoc )


Returns the name of the image document.

void ImageDocumentGetPageBounds( ImageDocument


imgDoc, NumberVariable top, NumberVariable left,
NumberVariable bottom, NumberVariable right )
Gets the page bounds of the document in page coordinates.

void ImageDocumentGetPageResolution_72dpi
( ImageDocument imgDoc, NumberVariable horz,
NumberVariable vert )
Returns the resolution of page coordinates in 72 dots per inch ( returns page
units per dot ).

void ImageDocumentGetPageResolution_Printer
( ImageDocument imgDoc, NumberVariable horz,
NumberVariable vert )
Returns the resolution of page coordinates in printer pixels ( returns page units
per printer pixel ).

void ImageDocumentGetPaperBounds( ImageDocument


imgDoc, NumberVariable top, NumberVariable left,
NumberVariable bottom, NumberVariable right )
Gets the paper bounds of the document in page coordinates.

void ImageDocumentGetPreferredViewRect( ImageDocument


imgDoc, NumberVariable top, NumberVariable left,
NumberVariable bottom, NumberVariable right )
Gets rectangle in view coordinates of the area that is by default displayed in
this mode.

void ImageDocumentGetReferencePointSize
( ImageDocument imgDoc, NumberVariable x,
NumberVariable y )
Gets the size of the reference point in view coordinates.

Component ImageDocumentGetRootComponent
( ImageDocument imgDoc )
Gets the root annotation of the image document.

TagGroup ImageDocumentGetTagGroup( ImageDocument


imgDoc )
Gets the tag group associated with the image document.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

238

void ImageDocumentGetUnzoomedPointSize( ImageDocument


imgDoc, NumberVariable x, NumberVariable y )
Gets the size of the unzoomed point in view coordinates.

void ImageDocumentGetViewExtent( ImageDocument


imgDoc, NumberVariable top, NumberVariable left,
NumberVariable bottom, NumberVariable right )
Gets the extent in view coordinates of the items visible in the current view
mode.

void ImageDocumentGetViewToWindowTransform
( ImageDocument imgDoc, NumberVariable off_x,
NumberVariable off_y, NumberVariable scale_x,
NumberVariable scale_y )
Returns the transformation from view to screen coordinates.

void ImageDocumentGetVisibleViewRect( ImageDocument


imgDoc, NumberVariable top, NumberVariable left,
NumberVariable bottom, NumberVariable right )
Gets the view coordinates of the rectangle visible in the view.

DocumentWindow ImageDocumentGetWindow( ImageDocument


imgDoc )
Returns the window displaying the document.

Boolean ImageDocumentHasBeenPlacedOnPage
( ImageDocument imgDoc )
Returns 'true' if the document has been layed out within the physical page.

void ImageDocumentHide( ImageDocument imgDoc )


Hides the given image document.

Boolean ImageDocumentIsInImageMode( ImageDocument


imgDoc )
Returns true if the view of the document is in image mode.

Boolean ImageDocumentIsInPageMode( ImageDocument


imgDoc )
Returns true if the view of the document is in page mode.

Boolean ImageDocumentIsValid( ImageDocument imgDoc )


Returns true if 'imageDocument' points to a valid object.

void ImageDocumentMaximizeRectInView( ImageDocument


imgDoc, Number top, Number left, Number bottom,
Number right )
Copyright 2012 Gatan Inc. All Rights Reserved.

239

DigitalMicrograph

Zooms the view so the rectangle is centered and maximal.

Boolean ImageDocumentPrint( ImageDocument imgDoc )


Print the image document, returning 'true' if successful.

void ImageDocumentRemoveFromUserInterface
( ImageDocument imgDoc )
Removes the image document from the list of user interface documents.

void ImageDocumentSaveToFile( ImageDocument imgDoc,


String handler, String fileName )
Saves the image document to the given file name using the I/O handler
specified.

void ImageDocumentSetCurrentViewAsUnzoomed
( ImageDocument imgDoc )
Makes the current view the unzoomed view.

void ImageDocumentSetName( ImageDocument imgDoc,


String name )
Sets the name of the image document.

void ImageDocumentSetRectInView( ImageDocument


imgDoc, Number v_t, Number v_l, Number v_b,
Number v_r, Number w_t, Number w_l, Number w_b,
Number w_r )
Zooms the view so the view rect (v_l,v_t,v_b,v_r) is displayed in the window
rect (w_l,w_t,w_b,w_r).

DocumentWindow ImageDocumentShow( ImageDocument


imgDoc )
Shows the given image document.

DocumentWindow ImageDocumentShowAtPosition
( ImageDocument imgDoc, Number x, Number y )
Shows the given image document at the application position (x,y).

DocumentWindow ImageDocumentShowAtRect( ImageDocument


imgDoc, Number top, Number left, Number bottom,
Number right )
Shows the given image document at the rect (top,left,bottom,right).

void ImageDocumentSwitchToImageMode( ImageDocument


imgDoc, ImageDisplay imgDisp )
Switches the view of the document to image mode focused on the display
'imgDisp'.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

240

void ImageDocumentSwitchToPageMode( ImageDocument


imgDoc )
Switches the view of the document to page mode.

void ImageDocumentUpdateDisplay( ImageDocument imgDoc


)
Updates the display of the image document.

Related Functions
ImageDocument =( ImageDocument, ! )
ImageDocument =( ImageDocument, ImageDocument )
ImageDocument CreateImageDocument( String title )
Creates an empty image document.

ImageDocument GetFrontImageDocument( )
Returns the front image document.

ImageDocument GetImageDocument( Number position )


Returns the image document by position with the application.

ImageDocument GetImageDocumentByID( Number id )


Returns the image document whose id is 'id'.

ImageDocument ImageDocumentNullify( ! )
ImageDocument ImageWindowGetImageDocument
( DocumentWindow window )
Gets the image document displayed in the window.

ImageDocument NewImageDocument( String title )


Creates an empty image document.

ImageDocument NewImageDocumentFromFile( String


path_name )
Creates a new image document from a file.
1.8.5.6.4 Image Object

Image Object
This chapter explains how to deal with images in the scripting language.

Copyright 2012 Gatan Inc. All Rights Reserved.

241

DigitalMicrograph

Image Data Types


The image data types supported in DigitalMicrograph are:
Image Data Types
Kind
Binary
Integer

Real
Complex
RGB

Size
1
1
1
2

Signed

2
4

Unsigned
Signed

Unsigned

Signed
Unsigned
Signed

4
8
8
16
4

Range
Smallest Value
0 or 1
1
-128 to 127
1
0 to 255
1
-32,768 to
1
32,767
0 to 65,535
1
-2,147,483,648 1
to
2,147,483,647
0 to
1
4,294,967,295
3.4E+38
1.5E-45
1.7E+308
5.0E-324
3.4E+38
1.5E-45
1.7E+308
5.0E-324
R/G/B/A 0 to 1
255

Where size is the size in bytes per pixel, range is the minimum to maximum value,
and smallest value is the smallest representable value closest to 0.
In addition to this list there is one more special case image data type, Packed
Complex, which is used to represent Hermitian complex data. It has 8 bytes per pixel,
but only stores one half of the pixels in an image. It is used to perform efficient Fast
Fourier Transforms (FFTs). However, this data type can't be used with image
expressions.
All number and image expressions are evaluated with floating point precision.
However, when assigning the value of an expression to an image, the value is
converted to the destination image's type before it is stored. For example, given an
unsigned 1 byte integer image a,

a = a + 1
This adds 1 to the value of every pixel in the image. If a pixel has a value of 1 it gets
set to 2. However, a pixel that has a value of 255 gets set to 255. The value is
clipped to fit in the integer range.

Image Variables and Creating Images

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

242

There are three different variable types in the script language which may be used to
refer to an image. Which is used depends on the image data type of the image
involved. The creation function used to create an image also depends on the desired
image data type. The following table illustrates the relationship between variable type,
creation function, and image data type.
Variable Type Creation
Kind
Function
realimage
BinaryImage() Binary
realimage
IntegerImage() Integer

realimage

RealImage()

Real

compleximage ComplexImage Complex


()
rgbimage

RGBImage()

RGB

Size
1
1
1
2
2
4
4
4
8
8

Signed

Signed
Unsigned
Signed
Unsigned
Signed
Unsigned

16
4

There are two ways that images may be created in a script:


Explicitly by calling a function
Implicitly by context

Explicit Creation
The image data types in DigitalMicrograph can be divided into five kinds. They are:
Binary Images
Integer Images
Real Images
Complex Images
RGB Images
There are five corresponding functions that are the principal ways of explicitly creating
images.

BinaryImages
The function used to create an binary image is:

realimage BinaryImage( string title, number


width, number height )
Where title is the title that would display in the image window, width the width
Copyright 2012 Gatan Inc. All Rights Reserved.

243

DigitalMicrograph

in pixels, and height the height in pixels. An example of creating an binary


image is:

number xsize = 256, ysize = 256


image myImage := BinaryImage( "My Image", xsize,
ysize )
myImage = remainder(irow+icol,2)
ShowImage( myImage )
This example creates an 256 x 256 pixel, binary image with the title "My
Image". It then sets all pixels in the image to a checker board pattern or 1's
and 0's. Finally it shows the image.

Integer Images
The function used to create an integer image is:

realimage IntegerImage( string title, number


size, number isSigned, number width, number
height )
Where title is the title that would display in the image window, size is the size
in bytes, isSigned 1 (true) if the data is to be signed (0 for unsigned), width the
width in pixels, and height the height in pixels. An example of creating an
integer image is:

number xsize = 256, ysize = 256


image myImage := IntegerImage( "My Image", 2, 1,
\
xsize, ysize )
myImage = irow
ShowImage( myImage )
This example creates an 256 x 256 pixel, 2 byte signed integer image with the
title "My Image". It then sets all pixels in the image to their row number. Finally
it shows the image.

Real Images
The function used to create a real image is:

realimage RealImage( string title, number size,


number width, number height )
Where title is the title that would display in the image window, size is the size
in bytes, width the width in pixels, and height the height in pixels. An example
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

244

of creating a real image is:

number xsize = 256, ysize = 256


image myImage := RealImage( "My Image", 4,
xsize, ysize )
myImage = icol
ShowImage( myImage )
This example creates an 256 x 256 pixel, 4 byte real image with the title "My
Image". It then sets all pixels in the image to their column number. Finally it
shows the image.

Complex Images
The function used to create a complex image is:

compleximage ComplexImage( string title, number


size, number width, number height )
Where t i t l e is the title that would display in the image window, size is the
size in bytes, wi dt h the width in pixels, and height the hei ght in pixels. An
example of creating an complex image is:

number xsize = 256, ysize = 256


compleximage myImage := ComplexImage( "My
Image", 8, \
xsize, ysize )
myImage = complex( irow, icol )
ShowImage( myImage )
This example creates an 256 x 256 pixel, 8 byte complex image with the title
"My Image". It then sets all pixels in the image to the expression complex
( i r ow, i col ) . This expression is a complex image expression where
the real part is the row number of every pixel and the imaginary part is the
column number of every pixel. Finally it shows the image.

RGB Images
The function used to create a RGB image is:

rgbimage RGBImage( string title, number size,


number width, number height )
Where t i t l e is the title that would display in the image window, size is the
size in bytes, width the wi dt h in pixels, and hei ght the height in pixels. An
example of creating an RGB image is:
Copyright 2012 Gatan Inc. All Rights Reserved.

245

DigitalMicrograph

number xsize = 256, ysize = 256


rgbimage myImage := RGBImage( "My Image", 4,
xsize, \
ysize )
myImage = rgb( irow, icol, sqrt( icol * irow ) )
ShowImage( myImage )
This example creates an 256 x 256 pixel, 4 byte RGB image with the title "My
Image". It then sets all pixels in the image to an interesting image expression.
Finally it shows the image. RGB images in DigitalMicrograph use 4 bytes per
pixel with the bytes corresponding to the alpha, red, green, and blue channels.
The alpha channel is not used for display. The r gb( ) function sets the alpha
channel to 0. There is another function r gba( ) that allows all four channels
to be set.

Implicit Creation
To increase the ease of use and eliminate the repetition of the step of creating an
image to store the result of an image expression, images may also be created
implicitly. Implicitly created images are always created by the script language in
response to the need to assign the value of an image expression to an actual image.
There are three ways that images are implicitly created.
Assignment By Value To An Image Letter
Assignment By Value To An Uninitialized Image Variable
Temporary Images
The image data type of the image created is context dependent on the image
expression that is to be assigned to it. A table listing the default image data types
follows.
Image Expression Type
realimage
compleximage
rgbimage

Default Image Data Type


Real 4 Byte
Complex 8 Byte
RGB 4 Byte

In any specific scripting situation if an image data type other than the default image
data type that would be implicitly created is desired it can be explicitly created by
using a creation function or by using the New command.

Assignment By Value To An Image Letter


If an image expression is assigned by value to an image letter and that
letter does not correspond to an existing image, one will be created of that
size. For example, if an image that corresponds to image letter a exists
and no image exists corresponding to image letter b,
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

246

b = a * 3
This will create an image of the same size as a. The image data type of
the created image depends on the image data type of a.
Assignment By Value To An Uninitialized Image Variable
When an image expression is assigned by value to an uninitialized image
variable an image of the correct size will be automatically created.
An uninitialized image variable is an image variable which does not reference
an image. All newly created image variables are uninitialized until an image is
assigned by reference or they are initialized by an implicit image creation.

For example,

given image abc,

image xyz
xyz = abc + 2
An image of the same size as abc will be created, xyz will be initialized to
reference it, and the result of the image expression abc + 2 will be assigned to
the new image.

Temporary Images
Temporary images are created when a pixel by pixel operation is used as an
argument to a whole image operation. A temporary image is created as
storage for the result of the pixel by pixel operation, which is then passed to
the whole image operation. After the whole image operation the temporary
image is deleted if it is no longer is used.Before we discuss image operations
it is important to understand the different representations of image data types
that DigitalMicrograph supports.

Image Calibrations
Images can be calibrated both in the spatial direction and its intensity. The following
example shows calibration of an image:

number xsize = 256, ysize = 256


image myImage := RealImage( "My Image", 4, xsize,
ysize )
myImage = icol
// in x and y dimension set one pizel to 0.1 nm
myImage.ImageSetDimensionOrigin( 0, 0 )
myImage.ImageSetDimensionScale( 0, 0.1 )

Copyright 2012 Gatan Inc. All Rights Reserved.

247

DigitalMicrograph

myImage.ImageSetDimensionUnitString(0, "nm" )
myImage.ImageSetDimensionOrigin(1, 0 )
myImage.ImageSetDimensionScale( 1, 0.1 )
myImage.ImageSetDimensionUnitString(1, "nm" )
// for intensity: subtract 100 from value, then
multiply by 10
// that gives the number of A.
myImage.ImageSetIntensityOrigin( 100 )
myImage.ImageSetIntensityScale( 10 )
myImage.ImageSetIntensityUnitString( "A" )
ShowImage( myImage )

Saving Images
Images can be saved using the following functions:

void Save( ImageReference image )


Save the image under its current filename.

void SaveImage( ImageReference image, string fileName


)
Save the image to the file_path in it's current file format.

void SaveAsGatan( ImageReference image, string


fileName )
Save the image in Gatan 3.0 file format to the specified location.

void SaveAsTiff( ImageReference image, string


fileName, number saveType )
Save the image in TIFF format to the specified file location. saveType = 1:
save data, saveType = 2: save display.

void SaveAsTiff( ImageReference image, string


fileName )
Save the image in TIFF format to the specified file location. Equivalent to using
Save Display As, so image will be stored as 1 byte integer.

void SaveAsGif( ImageReference image, string fileName


)
Save the image in GIF format to the specified file location. Equivalent to using
Save Display As, so image will be stored as 1 byte integer.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

248

void SaveAsPCX( ImageReference image, string fileName


)
Save the image in PCX format to the specified file location. Equivalent to using
Save Display As, so image will be stored as 1 byte integer.

void SaveAsPICT( ImageReference image, string


fileName )
Save the image in PICT format to the specified file location. Equivalent to using
Save Display As, so image will be stored as 1 byte integer.

void SaveAsRawData( ImageReference image, string


fileName )
Save the image in raw data format to the specified file location.

Methods
void ImageCalculateHistogram( ImageReference image,
ImageReference hist_image, Number complexMode,
Number min, Number max )
Calculates the histogram of 'image', mapping [min,max] into 'hist_image'.

void ImageCalculateMinMax( ImageReference image,


Number surveyTechnique, Number complexMode,
NumberVariable min, NumberVariable max )
Calculates the minimum and maximum value of 'image' using survey
technique 'surveyTechnique'.

ImageReference ImageClone( ImageReference img )


Returns a clone of 'img'.

void ImageCopyCalibrationFrom( ImageReference image,


ImageReference src_image )
Copy the calibration of 'src_image' to 'image'.

Number ImageCountImageDisplays( ImageReference )


Returns the number of image displays in which this image is displayed.

Number ImageCountImageDisplaysInImageDocument
( ImageReference, ImageDocument imgDoc )
Returns the number of image displays in the image document in which this
image is displayed.

ImageDisplay ImageCreateImageDisplay( ImageReference,


Number displayType )
Creates a new image display of type 'displayType' for the image.
Copyright 2012 Gatan Inc. All Rights Reserved.

249

DigitalMicrograph

Number ImageGetDataElementBitSize( ImageReference img


)
Returns the size of the data elements in bits.

Number ImageGetDataElementByteSize( ImageReference


img )
Returns the smallest number of bytes that can hold a data element.

Number ImageGetDataSeed( ImageReference img )


Gets the seed of the image data.

Number ImageGetDataType( ImageReference img )


Returns a long representing the data type.

String ImageGetDescriptionText( ImageReference img )


Gets the description text associated with the image.

void ImageGetDimensionCalibration( ImageReference,


Number dimension, NumberVariable origin,
NumberVariable scale, String units, Number
calibrationFormat )
Gets the calibration information of the given dimension.

Number ImageGetDimensionOrigin( ImageReference,


Number dimension )
Returns the origin of the given dimension of image.

Number ImageGetDimensionScale( ImageReference, Number


dimension )
Returns the scale of the given dimension of image.

Number ImageGetDimensionSize( ImageReference, Number


dimension )
Gets the size of the given dimension.

void ImageGetDimensionUnitInfo( ImageReference,


Number dimension, String canon_units,
NumberVariable power )
Copies the unit string of the given dimension of image to the buffer.

String ImageGetDimensionUnitString( ImageReference,


Number dimension )
Copies the unit string of the given dimension of image to the buffer.

Number ImageGetID( ImageReference )


Returns a unique identifier for the image.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

250

ImageDisplay ImageGetImageDisplay( ImageReference,


Number index )
Returns the given image display in which this image is displayed.

ImageDisplay ImageGetImageDisplayInImageDocument
( ImageReference, ImageDocument imgDoc, Number
index )
Returns the given image display in the image document in which this image is
displayed.

Number ImageGetIntensityOrigin( ImageReference )


Returns the origin of image's intensity.

Number ImageGetIntensityScale( ImageReference )


Returns the scale of image's intensity.

void ImageGetIntensityUnitInfo( ImageReference,


String canon_units, NumberVariable power )
Copies the unit string of image's intensity to the buffer.

String ImageGetIntensityUnitString( ImageReference )


Returns the units of the image's intensity.

String ImageGetLabel( ImageReference img )


Gets the label of the image as used in scripts.

String ImageGetName( ImageReference img )


Gets the name of the image.

Number ImageGetNumDimensions( ImageReference )


Returns number of dimensions of the image.

ImageDocument ImageGetOrCreateImageDocument
( ImageReference im )
Returns an image document containing the image, creating one if necessary.

TagGroup ImageGetTagGroup( ImageReference img )


Gets the tags associated with the image.

ScriptObject ImageGetUniqueID( ImageReference


image )
Returns the unique ID for this image. This id is globally unique across
sessions and locations.

Boolean ImageIsDataTypeBinary( ImageReference img )


Returns true if the data in the image is binary.

Copyright 2012 Gatan Inc. All Rights Reserved.

251

DigitalMicrograph

Boolean ImageIsDataTypeComplex( ImageReference img )


Returns true if the data in the image is complex.

Boolean ImageIsDataTypeFloat( ImageReference img )


Returns true if the data in the image is floating point.

Boolean ImageIsDataTypeInteger( ImageReference img )


Returns true if the data in the image is integral.

Boolean ImageIsDataTypePackedComplex( ImageReference


img )
Returns true if the data in the image is complex.

Boolean ImageIsDataTypeReal( ImageReference img )


Returns true if the data in the image is real.

Boolean ImageIsDataTypeRGB( ImageReference img )


Returns true if the data in the image is rgb.

Boolean ImageIsDataTypeSignedInteger( ImageReference


img )
Returns true if the data in the image is integral and signed.

Boolean ImageIsDataTypeUnsignedInteger
( ImageReference img )
Returns true if the data in the image is integral and unsigned.

Boolean ImageIsDimensionCalibrationDisplayed
( ImageReference im, Number dim )
Returns 'true' if the calibration of the 'dim'th dimension is displayed.

Boolean ImageIsIntensityCalibrationDisplayed
( ImageReference im )
Returns 'true' if the calibration of the intensity is displayed.

Boolean ImageIsValid( ImageReference image )


Returns true if 'image' is a valid object.

void ImageReadImageDataFromStream( ImageReference


image, ScriptObject stream, Number
stream_endianness )
Reads image data from the stream. The image data type determines how the
data is read, and 'stream_endianness' specifies the endianness of the stream,
1 == bigendian, 2 == littleendian.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

252

void ImageSetDescriptionText( ImageReference img,


String description )
Sets the description text associated with the image.

void ImageSetDimensionCalibration( ImageReference,


Number dimenstion, Number origin, Number scale,
String unitString, Number calibrationFormat )
Sets the calibration for the given dimension.

void ImageSetDimensionCalibrationDisplayed
( ImageReference im, Number dim, Boolean
do_display )
Sets whether or not to display the 'dim'th dimension in calibrated units to
'do_display'.

void ImageSetDimensionOrigin( ImageReference, Number


dimension, Number origin )
Sets the origin of the given dimension of image.

void ImageSetDimensionScale( ImageReference, Number


dimension, Number scale )
Sets the scale of the given dimension of image.

void ImageSetDimensionUnitInfo( ImageReference,


Number dimension, String canon_units, Number
power )
Sets the unit string of the given dimension of image.

void ImageSetDimensionUnitString( ImageReference,


Number dimension, String units )
Sets the unit string of the given dimension of image.

void ImageSetIntensityCalibrationDisplayed
( ImageReference im, Boolean do_display )
Sets whether or not to display the intensity in calibrated units to 'do_display'.

void ImageSetIntensityOrigin( ImageReference, Number


origin )
Sets the origin of image's intensity.

void ImageSetIntensityScale( ImageReference, Number


scale )
Sets the scale of image's intensity.

void ImageSetIntensityUnitInfo( ImageReference,


String canon_units, Number power )
Sets the unit string of image's intensity.

Copyright 2012 Gatan Inc. All Rights Reserved.

253

DigitalMicrograph

void ImageSetIntensityUnitString( ImageReference,


String units )
Sets the unit string of image's intensity.

void ImageSetName( ImageReference img, String name )


Sets the name of the image.
void ImageSwapImageDataByteOrder( ImageReference )
Swaps the byte order for each long word in the image. ABCD become DCBA.

void ImageWriteImageDataToStream( ImageReference


image, ScriptObject stream, Number
stream_endianness )
Writes image data to the stream. The image data type determines how the
data is written, and 'stream_endianness' specifies the endianness of the
stream, 1 == bigendian, 2 == littleendian.
1.8.5.6.5 Component Object

Component Object
Overview
Objects of type 'Component' are image document components, which include
annotations ( text, box, line, etc. ), image displays, masks, and regions of interest.
Components may be placed on a page, in an image display, or in a group, each of
which is represented by a type of component. The containing component is referred
to as the parent component, and it determines the coordinate system in which child
locations and sizes are specified ( the coordinate system of a container is its child
coordinate system, and the child's local coordinate system ). See "ImageDocument
Object" for a description of coordinate systems.
If a method requires or returns coordinates, they are usually specified in the
component's local coordinate system. However, if the method ends in 'InView' the
coordinates are in view coordinates. Note that none of the methods that set
coordinates use view coordinates. Thus, to manipulate the view of a component, use
the methods ending in 'InView' to get coordinates, and ImageDocument methods
such as ImageDocumentSetRectInView to position the component.
The annotation type, used by the function NewAnnotation and the method
ComponentGetType, are listed in the following table:
Annotation Type
2
3
4
5
6

Description
line annotation
arrow annotation
double arrow annotation
box annotation
oval annotation
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

8
9
13
15
17
19

254

spot mask annotation


array mask annotation
text annotation
bandpass mask annotation
group annotation
wedge mask annotation

The control points referred to in several of the methods are listed in the following table
Annotation Type
1
2
3

4
5
6
7

8
9
10
11
12
13
14
15

Description
start point of line
end point of line
position, used to move annotation ( the
position may be any point in the
annotation, so it is only good for
moving )
top-left of rectangular annotations, one
of the bandpass ovals
top-right of rectangular annotations,
one of the bandpass ovals
bottom-left of rectangular annotations,
one of the bandpass ovals
bottom-right of rectangular
annotations, one of the bandpass
ovals
other spot of spot mask
one vector of wedge and array masks
other vector of wedge and array
masks
top-left of other bandpass oval
top-right of other bandpass oval
bottom-left of other bandpass oval
bottom-right of other bandpass oval
one spot of spot mask

Methods
void ComponentAddChildAfter( Component parent,
Component child, Component annot_pos )
Adds 'child' to 'parent's list of sub-annotations after 'annot_pos'.

void ComponentAddChildAtBeginning( Component parent,


Component child )
Adds 'child' to the beginning of 'parent's list of sub-annotations.

Copyright 2012 Gatan Inc. All Rights Reserved.

255

DigitalMicrograph

void ComponentAddChildAtEnd( Component parent,


Component child )
Adds 'child' to the end of 'parent's list of sub-annotations.

void ComponentAddChildBefore( Component parent,


Component child, Component annot_pos )
Adds 'child' to 'parent's list of sub-annotations before 'annot_pos'.

Component ComponentAddNewComponent( Component parent,


Number type, Number f1, Number f2, Number f3,
Number f4 )
Creates a new annotation of type 'type' and adds it to 'parent'

Component ComponentClone( Component comp, Boolean


doDeepCopy )
Returns a identical copy of the component and all its sub-components,
copying associated images if 'doDeepCopy' is true.

Number ComponentCountChildren( Component comp )


Returns the number of sub components.

Number ComponentCountChildrenOfType( Component comp,


Number type )
Returns the number of sub-components of type 'type'.

void ComponentGetBoundingRect( Component comp,


NumberVariable t, NumberVariable l,
NumberVariable b, NumberVariable r )
Gets the bounding rect of the annotation.

void ComponentGetBoundingRectInView( Component comp,


NumberVariable t, NumberVariable l,
NumberVariable b, NumberVariable r )
Gets the bounding rect of the annotation.

Component ComponentGetChild( Component comp, Number


index )
Returns the 'index'th sub-component of 'comp'.

Component ComponentGetChildByID( Component comp,


Number ID )
Returns the component child of 'comp' with id 'ID'.

void ComponentGetChildToLocalTransform( Component


comp, NumberVariable off_x, NumberVariable
off_y, NumberVariable scale_x, NumberVariable
scale_y )
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

256

Gets the transformation from child to local coordinates.

void ComponentGetChildToPageTransform( Component


comp, NumberVariable off_x, NumberVariable
off_y, NumberVariable scale_x, NumberVariable
scale_y )
Gets the transformation from child to page coordinates.

void ComponentGetChildToViewTransform( Component


comp, NumberVariable off_x, NumberVariable
off_y, NumberVariable scale_x, NumberVariable
scale_y )
Gets the transformation from child to view coordinates.

void ComponentGetChildToWindowTransform( Component


comp, NumberVariable off_x, NumberVariable
off_y, NumberVariable scale_x, NumberVariable
scale_y )
Gets the transformation from child to window coordinates.

Boolean ComponentGetControlPoint( Component comp,


Number loc, NumberVariable x, NumberVariable
y )
Returns the value '(x,y)' associated with the control point, and returns 'true' if
the control point is valid

Component ComponentGetDescendentByID( Component comp,


Number ID )
Returns the component child of 'comp' with id 'ID'.

Number ComponentGetDrawingMode( Component comp )


Gets the drawing mode of the image doucment component.

Number ComponentGetFillMode( Component comp )


Gets the fill mode of the image doucment component.

Number ComponentGetFontAttributes( Component comp )


Gets the attributes of the component's font.

String ComponentGetFontFaceName( Component comp )


Gets the face name of the component's font.

void ComponentGetFontInfo( Component comp, String


faceName, NumberVariable attributes,
NumberVariable size, NumberVariable
text_encoding )
Gets a description of the component's font.

Copyright 2012 Gatan Inc. All Rights Reserved.

257

DigitalMicrograph

void ComponentGetFontInfo( Component comp, String


faceName, NumberVariable attributes,
NumberVariable size )
Gets a description of the component's font.

Number ComponentGetFontSize( Component comp )


Gets the point size of the component's font.

Number ComponentGetID( Component annot )


Gets the unique identifier of the annotation in the image document.

ImageDocument ComponentGetImageDocument( Component


annot )
Gets the image document associated with the annotation.

void ComponentGetLocalToPageTransform( Component


comp, NumberVariable off_x, NumberVariable
off_y, NumberVariable scale_x, NumberVariable
scale_y )
Gets the transformation from local to page coordinates.

void ComponentGetLocalToViewTransform( Component


comp, NumberVariable off_x, NumberVariable
off_y, NumberVariable scale_x, NumberVariable
scale_y )
Gets the transformation from local to view coordinates.

void ComponentGetLocalToWindowTransform( Component


comp, NumberVariable off_x, NumberVariable
off_y, NumberVariable scale_x, NumberVariable
scale_y )
Gets the transformation from local to window coordinates.

Component ComponentGetNthChildOfType( Component comp,


Number type, Number index )
Returns the nth sub-component of type 'type'.

Component ComponentGetParentComponent( Component comp


)
Gets the parent component of 'comp', if any.

ImageDisplay ComponentGetParentImageDisplay
( Component comp )
Gets the parent image display of the 'comp', if any.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

258

void ComponentGetRect( Component comp, NumberVariable


top, NumberVariable left, NumberVariable bottom,
NumberVariable right )
Gets the rectangle of the annotation.

void ComponentGetRectInView( Component comp,


NumberVariable top, NumberVariable left,
NumberVariable bottom, NumberVariable right )
Gets the rectangle of the annotation.

TagGroup ComponentGetTagGroup( Component annot )


Gets the tag group associated with the annotation.

Number ComponentGetType( Component annot )


Gets the type of the annotation.

Boolean ComponentIsOfType( Component annot, Number


type )
Gets the type of the annotation.

Boolean ComponentIsSelected( Component comp )


Returns whether the component is selected.

Boolean ComponentIsValid( Component annot )


Returns true if 'annot' points to a valid object.

void ComponentOffsetControlPoint( Component comp,


Number loc, Number x, Number y, Number
restrict_style )
Changes the control point 'loc' of 'comp' by '(x,y)' using restrictions specified
by 'restrict_style'.

void ComponentPositionAroundPoint( Component comp,


Number new_x, Number new_y, Number rel_x, Number
rel_y, Boolean horz, Boolean vert )
Moves the annotation so if 'horz', the 'rel_x' horizontal point in the bounding
rect is at 'new_x', and if 'vert', the 'rel_y' vertical point in the bounding rect is at
'new_y'

void ComponentRemoveFromParent( Component comp )


Removes the image document component from its parent.

void ComponentSetControlPoint( Component comp, Number


loc, Number x, Number y, Number
restrict_style )
Sets the control point 'loc' of 'comp' to '(x,y)' using restrictions specified by
'restrict_style'.

Copyright 2012 Gatan Inc. All Rights Reserved.

259

DigitalMicrograph

void ComponentSetDrawingMode( Component comp, Number


mode )
Sets the drawing mode of the image document component.

void ComponentSetFillMode( Component comp, Number


mode )
Sets the fill mode of the image document component.

void ComponentSetFontAttributes( Component comp,


Number attributes )
Sets the attributes of the component's font.

void ComponentSetFontFaceName( Component comp, String


face_name )
Sets the face name of the component's font.

void ComponentSetFontInfo( Component comp, String


face_name, Number attributes, Number size,
Number text_encoding )
Sets the font information of the component's font.

void ComponentSetFontInfo( Component comp, String


face_name, Number attributes, Number size )
Sets the font information of the component's font.

void ComponentSetFontSize( Component comp, Number


size )
Sets the point size of the component's font.

void ComponentSetRect( Component comp, Number top,


Number left, Number bottom, Number right )
Sets the rectangle of the annotation.

void ComponentSetSelected( Component comp, Boolean


select )
Sets the selection status of the component.

void ComponentTransformCoordinates( Component comp,


Number off_x, Number off_y, Number scale_x,
Number scale_y )
Transforms the component by the specified transform.

Related Functions
Component =( Component, ! )

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

260

Component =( Component, Component )


Component ComponentNullify( ! )
void GroupAnnotationUngroup( Component comp )
Ungroups the group annotation.

Component ImageDocumentGetComponentByID
( ImageDocument imgDoc, Number id )
Returns an annotation contained in this image document by id.

Component ImageDocumentGetRootComponent
( ImageDocument imgDoc )
Gets the root annotation of the image document.

Component NewArrowAnnotation( Number top, Number


left, Number bottom, Number right )
Creates a new arrow annotation.

Component NewBoxAnnotation( Number top, Number left,


Number bottom, Number right )
Creates a new box annotation.

Component NewComponent( Number type, Number f1,


Number f2, Number f3, Number f4 )
Creates a new annotaiton of type 'type'

Component NewDoubleArrowAnnotation( Number top,


Number left, Number bottom, Number right )
Creates a new double arrow annotation.

Component NewGroupAnnotation( )
Creates a new group annotation.

Component NewLineAnnotation( Number top, Number left,


Number bottom, Number right )
Creates a new line annotation.

Component NewOvalAnnotation( Number top, Number left,


Number bottom, Number right )
Creates a new oval annotation.

Component NewPictureAnnotation( Number top, Number


left, Number bottom, Number right, Number
picture )
Creates a new picture annotation.

Copyright 2012 Gatan Inc. All Rights Reserved.

261

DigitalMicrograph

Component NewTextAnnotation( Number left, Number top,


String text, Number size )
Creates a new text annotation.

void PictureAnnotationSetPicture( Component comp,


Number picture )
Sets the picture of an annotation.

Number TextAnnotationGetAlignment( Component comp )


Gets the alignment of the text in the text annotation.

void TextAnnotationGetFixedPoint( Component comp,


NumberVariable x, NumberVariable y )
Gets the fixed point of the text annotation.

Number TextAnnotationGetResizeStyle( Component


comp )
Gets the resize style of the text annotation.

String TextAnnotationGetText( Component comp )


Gets the text of a text annotation.

void TextAnnotationSetAlignment( Component comp,


Number alignment )
Sets the alignment of the text in the text annotation.

void TextAnnotationSetFixedPoint( Component comp,


Number x, Number y )
Sets the fixed point of the text annotation.

void TextAnnotationSetResizeStyle( Component comp,


Number style )
Sets the resize style of the text annotation.

void TextAnnotationSetText( Component comp, String


text )
Sets the text of a text annotation.
1.8.5.6.6 ImageDisplay Object

ImageDisplay Object
Overview
Image displays are components used to display the contents of images. Component
methods may be used to position these on the page, but specialized methods such
as ImageDisplaySetImageRect are supplied to allow the position and size of the
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

262

image portion of the display ( excluding borders, captions, etc ) to be specified. As


with other methods dealing with coordinates, use those ending in 'InView' to find the
coordinates of the display as seen in a window. Currently only raster and rgb image
displays have a well-defined coordinate system for child components, and this
coordinate system has its origin at the top-left of the displayed image, and units
equivalent to image pixels.
Image display types may be one of the following:
Image Display Type
-2
1
2
3
4
7

Description
Best image display*
Raster image display
Surface plot image display
Line plot image display
RGB image display
Spreadsheet image display

*This is only used when setting a display type, and it produces line plots for 1d images, and raster or rgb displays for 2-d data.

ImageDisplay properties
ImageDisplays show the data that is contained in the image to the user. To represent
the data on the screen the data values stored in the image need to be translated to
gray scale or RGB values. The whole mechanism used by DigitalMicrograph to
accomplish this is discussed in "About Image Displays". All the same operations that
were described in that section can also be performed by script. So you can get and
set the DisplayType, survey mode, contrast limits, contrast and brightness etc. See
the following script for a simple example:

// open image
image myImage := GetFrontImage()
ImageDisplay imageDisp = myImage.
ImageGetImageDisplay( 0 )
// get display info
number low, high, bright, contrast
imageDisp.ImageDisplayGetContrastLimits( low, high
)
imageDisp.ImageDisplayGetContrastParameters
( bright, contrast )
// get color table
Image colorTable := imageDisp.
ImageDisplayGetInputColorTable(

Copyright 2012 Gatan Inc. All Rights Reserved.

263

DigitalMicrograph

// modify it
colorTable = rgb( icol + 16 * irow, 255 - icol 16 * irow, 128 )
// apply color table
imageDisp.ImageDisplaySetInputColorTable
( colorTable )

Using ImageDisplay key listeners


You can add listeners to image displays so that certain actions can be performed
when a user hits keys while an image display is in the foreground. To add a key
listener is a multi step process:
1. Write a script that contains a function that returns a number and takes as an
argument a number. For example

number HandleKey( Number key )


{
Result( "key = " + key + "\n" )
Beep()
return 1
}

2. Install this script as a library. See Installing Scripts.


The function in the script above will be called when the key event occurs. For this
function to be available at that time it should to be installed as a library.
3. Attach the listener to the image display using the following script

// open image
image myImage := GetFrontImage()
ImageDisplay imageDisp = myImage.
ImageGetImageDisplay( 0 )
// add listener
imageDisp.ImageDisplayAddKeyListener( "Test",
"HandleKey( key )" )
4. Now select the front image and hit any key. The key number will appear in the
results window and you will here a beep. This happens because on hitting a key the
listener executes the following script (when hitting the 'a' key)

number key=97; exit(HandleKey( key ))


Since you had installed a script library that contains the function HandleKey( number
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

264

key) that function will now be called, resulting in the print-out and beep.
5. Remove the listener using the following script

// open image
image myImage := GetFrontImage()
ImageDisplay imageDisp = myImage.
ImageGetImageDisplay( 0 )
// add listener
imageDisp.ImageDisplayRemoveKeyListener( "Test" )

Methods
void ImageDisplayAccumulateROIsToMask( ImageDisplay
imgDisp, ImageReference mask, Number top, Number
left, Number bottom, Number right, Number
mask_val )
Sets mask to mask_val at points in imageDisplay's rois

void ImageDisplayAddKeyListener( ImageDisplay


imgDisp, String listener_key, String
listener_script )
Adds the listener_script to the key listener list under the tag listener_key.

void ImageDisplayAddROI( ImageDisplay imgDisp, ROI


roi )
Adds the roi to this image display.

void ImageDisplayChangeDisplayType( ImageDisplay


imgDisp, Number new_type )
Changes the type of the image display.

Number ImageDisplayCountROIs( ImageDisplay imgDisp )


Returns the number of ROIs on this image display.

void ImageDisplayDeleteROI( ImageDisplay imgDisp, ROI


roi )
Deletes the roi from this image display.

Boolean ImageDisplayDoesROIExist( ImageDisplay


imgDisp, String name )
Determines whether the given ROI exists on this image display.

void ImageDisplayExportToFile( ImageDisplay imgDisp,


String format, String file_name )

Copyright 2012 Gatan Inc. All Rights Reserved.

265

DigitalMicrograph

Exports the display to the file 'file_name' using the format 'format'.

ImageReference ImageDisplayGetBufferedImage
( ImageDisplay imgDisp )
Gets the image resulting from the contrast transformation.

Number ImageDisplayGetComplexMode( ImageDisplay


imgDisp )
Gets the complex mode of the display.

Number ImageDisplayGetComplexModeRange( ImageDisplay


imgDisp )
Gets the parameter used in converting complex to real.

void ImageDisplayGetContrastLimits( ImageDisplay


imgDisp, NumberVariable low, NumberVariable high
)
Gets the contrast limits of the display.

Number ImageDisplayGetContrastMode( ImageDisplay


imgDisp )
Returns the contrast mode.

void ImageDisplayGetContrastParameters( ImageDisplay


imgDisp, NumberVariable bright, NumberVariable
contrast )
Gets the parameters for the contrast mode.

ImageReference ImageDisplayGetDisplayedImage
( ImageDisplay imgDisp )
Gets the image that is actually displayed in the image display.

void ImageDisplayGetDisplayedLayers( ImageDisplay


imgDisp, NumberVariable start, NumberVariable
end )
Gets the layers that are summed into the display.

Number ImageDisplayGetDisplayType( ImageDisplay


imgDisp )
Returns type of the image display.

Boolean ImageDisplayGetDoAutoSurvey( ImageDisplay


imgDisp )
Determines whether min and max are determined automatically.

ImageReference ImageDisplayGetExportImage
( ImageDisplay imgDisp, Number mode,
ImageDisplay clut_display )
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

266

Gets the image representation of the image as it appears on the screen at full
resolution.

ImageReference ImageDisplayGetImage( ImageDisplay


imgDisp )
Returns the single image displayed by the image display.

void ImageDisplayGetImageAdjustRect( ImageDisplay


imgDisp, NumberVariable top, NumberVariable
left, NumberVariable bottom, NumberVariable
right )
Returns the image display outside the image rect

void ImageDisplayGetImageAdjustRectInView
( ImageDisplay imgDisp, NumberVariable top,
NumberVariable left, NumberVariable bottom,
NumberVariable right )
Returns the image display outside the image rect in view coordinates

void ImageDisplayGetImageRect( ImageDisplay imgDisp,


NumberVariable top, NumberVariable left,
NumberVariable bottom, NumberVariable right )
Gets the bounds of the image in the image display.

void ImageDisplayGetImageRectInView( ImageDisplay


imgDisp, NumberVariable top, NumberVariable
left, NumberVariable bottom, NumberVariable
right )
Gets the bounds of the image in the image display in view coordinates.

ImageReference ImageDisplayGetInputColorTable
( ImageDisplay imgDisp )
Gets the input color table for the display.

ImageReference ImageDisplayGetIntensityTransformation
( ImageDisplay imgDisp )
Gets the ITT of the display.

Number ImageDisplayGetMinimumContrast( ImageDisplay


imgDisp )
Gets the minimum contrast of the display.

ImageReference ImageDisplayGetOutputColorTable
( ImageDisplay imgDisp )
Gets the output color table for the display.

Copyright 2012 Gatan Inc. All Rights Reserved.

267

DigitalMicrograph

ROI ImageDisplayGetROI( ImageDisplay imgDisp, Number


index )
Returns the given ROI on this image display.

Number ImageDisplayGetROISelectionStyle( ImageDisplay


imgDisp, ROI r )
Gets the selection style of the ROI in the image display.

Number ImageDisplayGetSurveyTechnique( ImageDisplay


imgDisp )
Gets the survey technique of the display.

Boolean ImageDisplayIsCaptionOn( ImageDisplay imgDisp


)
Returns true if captions are drawn.

Boolean ImageDisplayIsROISelected( ImageDisplay


imgDisp, ROI roi )
Determines whether the given ROI is selected on this image display.

Boolean ImageDisplayIsValid( ImageDisplay imgDisp )


Returns true if 'imageDisplay' points to a valid object.

ROI ImageDisplayLookupROI( ImageDisplay imgDisp,


String name )
Returns the given ROI on this image display.

ROI ImageDisplayLookupROIByID( ImageDisplay imgDisp,


Number id )
Returns the ROI with the given id on this image display.

void ImageDisplayRemoveKeyListener( ImageDisplay


imgDisp, String listener_key )
Removes the listener script with the tag listener_key from the key listener list.

void ImageDisplaySetCaptionOn( ImageDisplay imgDisp,


Boolean on )
Sets whether to draw captions.

void ImageDisplaySetComplexMode( ImageDisplay


imgDisp, Number mode )
Sets the complex mode of the display.

void ImageDisplaySetComplexModeRange( ImageDisplay


imgDisp, Number range )
Sets the parameter used in converting complex to real.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

268

void ImageDisplaySetContrastLimits( ImageDisplay


imgDisp, Number low, Number hight )
Sets the contrast limits of the display.

void ImageDisplaySetContrastMode( ImageDisplay


imgDisp, Number mode )
Sets the contrast mode.

void ImageDisplaySetContrastParameters( ImageDisplay


imgDisp, Number bright, Number contrast )
Gets the parameters for the contrast mode.

void ImageDisplaySetDisplayedLayers( ImageDisplay


imgDisp, Number start, Number end )
Sets the layers that are summed into the display.

void ImageDisplaySetDoAutoSurvey( ImageDisplay


imgDisp, Boolean do_survey )
Sets whether min and max are determined automatically.

void ImageDisplaySetImageRect( ImageDisplay imgDisp,


Number top, Number left, Number bottom, Number
right )
Sets the bounds of the image part of the image display.

void ImageDisplaySetInputColorTable( ImageDisplay


imgDisp, ImageReference clut )
Sets the input color table of the display.

void ImageDisplaySetIntensityTransformation
( ImageDisplay imgDisp, ImageReference itt )
Sets the ITT of the display.

void ImageDisplaySetMinimumContrast( ImageDisplay


imgDisp, Number contrast )
Sets the minimum contrast of the display.

void ImageDisplaySetROISelected( ImageDisplay


imgDisp, ROI roi, Boolean select )
Sets the selection status of the region of interest in the image display.

void ImageDisplaySetROISelectionStyle( ImageDisplay


imgDisp, ROI r, Number style )
Sets the selection style of the roi in the imag display.

void ImageDisplaySetSurveyTechnique( ImageDisplay


imgDisp, Number tech )
Sets the survey technique of the display.
Copyright 2012 Gatan Inc. All Rights Reserved.

269

DigitalMicrograph

Related Functions
ImageDisplay =( ImageDisplay, Component )
ImageDisplay =( ImageDisplay, ! )
ImageDisplay =( ImageDisplay, ImageDisplay )
void ApplyDataBar( ImageDisplay imgDisp )
Applies a data bar to the image.

ImageDisplay ImageDisplayNullify( ! )
ImageDisplay ImageDocumentAddImageDisplay
( ImageDocument imgDoc, ImageReference image,
Number displayType )
Adds the given image and an image display for it of the given type.

ImageDisplay ImageDocumentGetImageModeDisplay
( ImageDocument imgDoc )
Gets the image display targeted by the current image mode.

ImageReference NewLiveFFT( ImageDisplay imageDisplay,


ROI roi, Boolean reduce )
Creates a new live fft of the area in 'roi', that is reduced if 'reduce' is 'true'

ImageReference NewLiveHistogram( ImageDisplay


imageDisplay, ROI roi, Number num_channels )
Creates a new live histogram of the area in 'roi', binned by 'num_channels'

ImageReference NewLiveProfile( ImageDisplay


imageDisplay, Number start_x, Number start_y,
Number end_x, Number end_y, Number width )
Creates a new live profile from (start_x,start_y) to (end_x,end_y)
1.8.5.6.7 RasterImageDisplay Object

RasterImageDisplay Object
Overview
A RasterImageDisplay is the display type most often used to view an image. The
RasterImageDisplay class extends ImageDisplay and adds a few functions. All
examples in the ImageDisplay section actually use RasterImageDisplays.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

270

The functionality added to this sub-class relates to thresholds. See the chapter on
Thresholding in the Particle Analysis section.
See the following example on how to use the new functions:

// open image
image myImage := GetFrontImage()
ImageDisplay imageDisp = myImage.ImageGetImageDisplay
( 0 )
number low, high
imageDisp.ImageDisplayGetContrastLimits( low, high )
number width = myImage.ImageGetDimensionSize( 0 )
number height = myImage.ImageGetDimensionSize( 1 )
// trun thresholding on
imageDisp.RasterImageDisplaySetThresholdOn( 1 )
// set limits
imageDisp.RasterImageDisplaySetThresholdLimits( low,
(low + high)/2 )
// create mask image, should be binary or 8 bit
signed or unsigned
image mask := IntegerImage("Mask", 1, 0, width,
height )
imageDisp.RasterImageDisplayAddThresholdToMask( mask,
0, 0, height, width )
// turn thresholding off
imageDisp.RasterImageDisplaySetThresholdOn( 0 )
// display the mask
ShowImage( mask )

Methods
void RasterImageDisplayAddThresholdToMask
( RasterImageDisplay rid, ImageReference mask,
Number top, Number left, Number bottom, Number
right )
Sets the points in mask to 1 if they lie within the threshold.

Copyright 2012 Gatan Inc. All Rights Reserved.

271

DigitalMicrograph

void RasterImageDisplayGetThresholdLimits
( RasterImageDisplay rid, NumberVariable low,
NumberVariable high )
Gets the threshold limits of the display.

Boolean RasterImageDisplayIsThresholdOn
( RasterImageDisplay rid )
Determines whether the thresholding overlay is on or off.

void RasterImageDisplaySetThresholdLimits
( RasterImageDisplay rid, Number low, Number
high )
Sets the threshold limits of the display.

void RasterImageDisplaySetThresholdOn
( RasterImageDisplay rid, Boolean on )
Sets whether the thresholding overlay is on or off.

Related Functions
RasterImageDisplay =( RasterImageDisplay dst, ! )
RasterImageDisplay =( RasterImageDisplay dst,
RasterImageDisplay rid )
RasterImageDisplay =( RasterImageDisplay dst,
ImageDisplay id )
ImageReference CreateMaskFromAnnotations
( RasterImageDisplay rid, Number filter_length,
Boolean is_opaque, NumberVariable has_mask )
RasterImageDisplay RasterImageDisplayNullify( ! )
1.8.5.6.8 SurfacePlotImageDisplay Object

SurfacePlotImageDisplay Object
Overview
The SurfacePlotImageDisplay shows a 3D representation of intensities in a 2D image.
You can control all the setings as explained in "Using Surface Plot Image Displays"
from the script functions supplied in this class.
The shape of a surface plot image display is given by the x,y offset of the x-axis, the x,
y offset of the y-axis, and the y-offset of the z-axis, denoted '(x_axis_x,x_axis_y)',
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

272

'(y_axis_x,y_axis_y)', and 'z_axis' in the script methods. In all of these offsets, positive
x points to the left and positive y points down. Only the relative sizes of these values
matter, for the coordinates are scaled to fit in the display bounds.

Methods
void SurfacePlotImageDisplayGetCubeAxes
( SurfacePlotImageDisplay spid, NumberVariable
x_axis_x, NumberVariable x_axis_y,
NumberVariable y_axis_x, NumberVariable
y_axis_y, NumberVariable z_axis )
Gets the points describing the surface plot cube.

void SurfacePlotImageDisplayGetCubePoint
( SurfacePlotImageDisplay spid, Number
which_point, NumberVariable x, NumberVariable
y )
Gets the child coordinates of the cube point indicated by 'which_point'

Boolean SurfacePlotImageDisplayIsShadingOn
( SurfacePlotImageDisplay spid )
Determines whether shading is on or off.

void SurfacePlotImageDisplaySetCubeAxes
( SurfacePlotImageDisplay spid, Number x_axis_x,
Number x_axis_y, Number y_axis_x, Number
y_axis_y, Number z_axis )
Sets the points describing the surface plot cube.

void SurfacePlotImageDisplaySetShadingOn
( SurfacePlotImageDisplay spid, Boolean on )
Sets whether shading is on or off.

Related Functions
SurfacePlotImageDisplay =( SurfacePlotImageDisplay
dst, ImageDisplay id )
SurfacePlotImageDisplay =( SurfacePlotImageDisplay
dst, ! )
SurfacePlotImageDisplay =( SurfacePlotImageDisplay
dst, SurfacePlotImageDisplay spid )
SurfacePlotImageDisplay
SurfacePlotImageDisplayNullify( ! )
Copyright 2012 Gatan Inc. All Rights Reserved.

273

DigitalMicrograph

1.8.5.6.9 LinePlotImageDisplay Object

LinePlotImageDisplay Object
Overview
For LinePlotImageDisplay you can control from script all of the parameters that have
been explained under "Using Line Plot Image Displays" and "Using Line Plot Legends
".
Here we give a simple example that creates an image and displays it in a
LinePlotImageDisplay, with some properties set:

// create image and image document


ImageDocument imageDoc = CreateImageDocument( "New
ImageDocument" )
number width = 256
number height = 5
image img := RealImage("Line Plot Test", 4, width,
height )
img = sin( irow + icol/100 )
// add LinePlotImageDisplay to ImageDocument
ImageDisplay imgdsp = imageDoc.
ImageDocumentAddImageDisplay( img, 3 )
imgdsp.LinePlotImageDisplaySetContrastLimits( 1.1, 1.1 )
imgdsp.LinePlotImageDisplaySetDoAutoSurvey( 0, 0 )
// draw fill and line for slice 0
imgdsp.LinePlotImageDisplaySetSliceDrawingStyle(0,
3)
// set line color to red
imgdsp.LinePlotImageDisplaySetSliceComponentColor
(0, 0, 1, 0, 0)
// set fill color to yellow
imgdsp.LinePlotImageDisplaySetSliceComponentColor
(0, 1, 0.9, 0.9, 0)
// draw fill for slice 1 and 2
imgdsp.LinePlotImageDisplaySetSliceDrawingStyle(1,
2)
imgdsp.LinePlotImageDisplaySetSliceDrawingStyle(2,
2)
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

274

// draw line for slice 3 and 4


imgdsp.LinePlotImageDisplaySetSliceDrawingStyle(3,
1)
imgdsp.LinePlotImageDisplaySetSliceDrawingStyle(4,
1)
imageDoc.ImageDocumentShow()
Methods
Number LinePlotImageDisplayCountSlices
( LinePlotImageDisplay lpid )
Returns the number of slices in the line plot.

Number LinePlotImageDisplayGetBaseIntensity
( LinePlotImageDisplay lpid )
Returns the base intensity of the line plot.

void LinePlotImageDisplayGetContrastLimits
( LinePlotImageDisplay lpid, NumberVariable
lowLimit, NumberVariable highLimit )
Gets the lowest and higest intensities displayed.

void LinePlotImageDisplayGetDisplayedChannels
( LinePlotImageDisplay lpid, NumberVariable
leftChannel, NumberVariable rightChannel )
Gets the leftmost and rightmost displayed channels.

void LinePlotImageDisplayGetDoAutoSurvey
( LinePlotImageDisplay lpid, NumberVariable
doAutoSurveyLow, NumberVariable doAutoSurveyHigh
)
Gets whether to auto-survey is done on the high and low intensity limits.

Number LinePlotImageDisplayGetSlice
( LinePlotImageDisplay lpid )
Returns slice currently displayed at the bottom.

void LinePlotImageDisplayGetSliceComponentColor
( LinePlotImageDisplay lpid, Number slice_index,
Number comp_index, NumberVariable r,
NumberVariable g, NumberVariable b )
Returns the color of the 'comp_index'th component of the 'slice_index'th slice.

Copyright 2012 Gatan Inc. All Rights Reserved.

275

DigitalMicrograph

Number LinePlotImageDisplayGetSliceDrawingStyle
( LinePlotImageDisplay lpid, Number
slice_index )
Returns the drawing style of the 'slice_index'th slice.

void LinePlotImageDisplayGetTrackingStyle
( LinePlotImageDisplay lpid, NumberVariable
track_style_x, NumberVariable track_style_y )
Gets the tracking style of the line plot.

Boolean LinePlotImageDisplayIsBackgroundOn
( LinePlotImageDisplay lpid )
Returns true if the background is erased.

Boolean LinePlotImageDisplayIsFilled
( LinePlotImageDisplay lpid )
Returns true if the line plot is filled.

Boolean LinePlotImageDisplayIsFrameOn
( LinePlotImageDisplay lpid )
Returns true if the frame is drawn.

Boolean LinePlotImageDisplayIsGridOn
( LinePlotImageDisplay lpid )
Returns true if the grid is displayed on.

void LinePlotImageDisplaySetBackgroundOn
( LinePlotImageDisplay lpid, Boolean on )
Sets whether to erase the background.

void LinePlotImageDisplaySetBaseIntensity
( LinePlotImageDisplay lpid, Number
base_intensity )
Sets the base intensity of the line plot.

void LinePlotImageDisplaySetContrastLimits
( LinePlotImageDisplay lpid, Number lowLimit,
Number highLimit )
Sets the lowest and highest intensities displayed.

void LinePlotImageDisplaySetDisplayedChannels
( LinePlotImageDisplay lpid, Number leftChannel,
Number rightChannel )
Sets the leftmost and rightmost displayed channels.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

276

void LinePlotImageDisplaySetDoAutoSurvey
( LinePlotImageDisplay lpid, Boolean
doAutoSurveyLow, Boolean doAutoSurveyHigh )
Sets whether to do auto-survey on the high and low intensity limits.

void LinePlotImageDisplaySetFilled
( LinePlotImageDisplay lpid, Boolean on )
Sets whether to fill the lineplot.

void LinePlotImageDisplaySetFrameOn
( LinePlotImageDisplay lpid, Boolean on )
Sets whether to draw the frame.

void LinePlotImageDisplaySetGridOn
( LinePlotImageDisplay lpid, Boolean on )
Sets whether to draw the grid.

void LinePlotImageDisplaySetSlice
( LinePlotImageDisplay lpid, Number slice )
Sets the slice currently displayed at the bottom.

void LinePlotImageDisplaySetSliceComponentColor
( LinePlotImageDisplay lpid, Number slice_index,
Number comp_index, Number r, Number g, Number
b )
Sets the color of the 'comp_index'th component of the 'slice_index'th slice.

void LinePlotImageDisplaySetSliceDrawingStyle
( LinePlotImageDisplay lpid, Number slice_index,
Number style )
Sets the drawing style of the 'slice_index'th slice.

void LinePlotImageDisplaySetTrackingStyle
( LinePlotImageDisplay lpid, Number
track_style_x, Number track_style_y )
Sets the tracking style of the line plot.

Related Functions
LinePlotImageDisplay =( LinePlotImageDisplay dst,
LinePlotImageDisplay lpid )
LinePlotImageDisplay =( LinePlotImageDisplay
dst, ! )
LinePlotImageDisplay =( LinePlotImageDisplay dst,
ImageDisplay id )
Copyright 2012 Gatan Inc. All Rights Reserved.

277

DigitalMicrograph

LinePlotImageDisplay LinePlotImageDisplayNullify
( ! )
1.8.5.6.10 ROI Object

ROI Object
Overview
ROI's are described in the section "Using Regions of Interest". The scripting language
allows access to all the features available through the normal user interface.

Adding ROI to an image


ROI's can be added to all ImageDisplay types except SurfacePlotImageDisplay. In
addition the ROI of type range can only by used on a LinePlotImageDisplay.
An example script that adds different ROI's to a RasterImageDisplay follows:

// create the ImageDocument


ImageDocument imageDoc = CreateImageDocument( "New
ImageDocument" )
imageDoc.ImageDocumentEnsurePlacedOnPage()
// create a float image of 256 by 256
number width = 256, height = 256
Image img := RealImage("dummy", 4, width, height )
img = irow
// add the new image to the imageDocument
imageDoc.ImageDocumentAddImage( img )
// get the display object of the image
ImageDisplay imgDisplay = img.ImageGetImageDisplay
(0 )
// create a rectangle ROI
ROI myROI1 = NewROI( )
myROI1.ROISetRectangle( height/4, width/4,
height/2, width/2 )
imgDisplay.ImageDisplayAddROI( myROI1 )
//create a line ROI
ROI myROI2 = NewROI( )
myROI2.ROISetLine( height/4, width/4, height/2,
width/2 )
myROI2.ROISetColor( 0, 1, 0 )
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

278

imgDisplay.ImageDisplayAddROI( myROI2 )
// create a vertex ROI
ROI myROI3 = NewROI( )
myROI3.ROISetPoint( 200, 200 )
myROI3.ROIAddVertex( 225, 225 )
myROI3.ROIAddVertex( 250, 200 )
myROI3.ROIAddVertex( 225, 175 )
myROI3.ROIAddVertex( 200, 200 )
myROI3.ROISetColor( 0, 0, 1 )
imgDisplay.ImageDisplayAddROI( myROI3 )
// show image
imageDoc.ImageDocumentShow()
Getting and Setting properties of ROI
ROI have the following properties which can be set in the scripting language:
Property
name

Default value

label
id

unique integer

color

red (1, 0 , 0)

moveable
deletable
resizable
volatile

yes
yes
yes
yes

Copyright 2012 Gatan Inc. All Rights Reserved.

Description
string used to identify
ROI. Allows finding ROI
with function "ROI
ImageDisplayLookupROI
( ImageDisplay imgDisp,
String name ) "
Labels are displayed near
the ROI
integer used to identify
ROI. Allows finding ROI
with function "ROI
GetROIFromID( Number
id ) " or "ROI
ImageDisplayLookupROI
ByID( ImageDisplay
imgDisp, Number id ) "
All ROIs are drawn in a
striped pattern with half of
the pixels white and the
other half set to the
specified color. If the ROI
is not volatile, it is drawn
solidly in the specified
color.

If volatile is false then the


ROI does not disappear

279

DigitalMicrograph

closed

when drawing another


ROI. A non-volatile ROI is
drawn in a solid color, as
opposed to the striped
pattern of volatile ROIs.
An ROI is closed if the
end of the last vertex
coincides with the start of
the first vertex.

The properties moveable, deletable, resizable and volatile can be used to assist the
user in interacting with the ROI. For example if you create an image and place an ROI
on it that you want the user to move somewhere, you can set the ROI to be not
deletable to prevent the user from deleting the ROI and making your procedure
useless.

Finding ROIs
Given an ImageDisplay, you can find all ROIs that are located on it using hte functions
"Number ImageDisplayCountROIs( ImageDisplay imgDisp ) " and "ROI
ImageDisplayGetROI( ImageDisplay imgDisp, Number index ) ".
The following example shows an example of using those functions:

// open image
image myImage := GetFrontImage()
ImageDisplay imageDisp = myImage.ImageGetImageDisplay
( 0 )
number count = imageDisp.ImageDisplayCountROIS()
number index
for (index = 0; index < count; ++index )
{
ROI currentROI = imageDisp.ImageDisplayGetROI
( index )
Result( "ROI named " + currentROI.ROIGetName() +
\
" has " + currentROI.ROICountVertices() + "
vertices.\n" )
}
Methods
void ROIAddToMask( ROI roi, ImageReference mask,
Number top, Number left, Number bottom, Number
right )
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

280

Add the region of interest to the image within the bounds of the specified
rectangle.

void ROIAddVertex( ROI roi, Number x, Number y )


Add a vertex with the given coordinates to the region of interest.

void ROIClearVertices( ROI roi )


Remove all vertices from the region of interest.

ROI ROIClone( ROI roi )


Returns a clone of the roi.

Boolean ROIContainsPoint( ROI roi, Number x, Number y


)
Returns whether the region of interest encloses the given point.

Number ROICountVertices( ROI roi )


Return the number of vertices comprising the region of interest.

void ROIDeleteVertex( ROI roi, Number index )


Delete the given vertex from the region of interest.

void ROIGetColor( ROI roi, NumberVariable r,


NumberVariable g, NumberVariable b )
Stores the color of the region of interest into the variables. Each number will
be in the range of 0 to 1.

Boolean ROIGetDeletable( ROI roi )


Return whether the region of interest is deletable or not.

Number ROIGetID( ROI roi )


Return the ID for the region of interest.

String ROIGetLabel( ROI roi )


Return the label of the region of interest.

void ROIGetLine( ROI roi, NumberVariable sx,


NumberVariable sy, NumberVariable ex,
NumberVariable ey )
Fill in the start and end points of the line represented by the region of interest.

Boolean ROIGetMoveable( ROI roi )


Return whether the region of interest is moveable or not.

String ROIGetName( ROI roi )


Return the name of the region of interest.

Copyright 2012 Gatan Inc. All Rights Reserved.

281

DigitalMicrograph

void ROIGetPoint( ROI roi, NumberVariable x,


NumberVariable y )
Return the coordinates of the point represented by this region of interest.

void ROIGetRange( ROI roi, NumberVariable start,


NumberVariable end )
Fills in the start and end columns of the range represented by the region of
interest.

void ROIGetRectangle( ROI roi, NumberVariable top,


NumberVariable left, NumberVariable bottom,
NumberVariable right )
Fill in the coordinates of the rectangle represented by the region of interest.

Boolean ROIGetResizable( ROI roi )


Return whether the region of interest is resizable or not.

void ROIGetVertex( ROI roi, Number index,


NumberVariable x, NumberVariable y )
Return the coordinates of the given vertex of the region of interest.

Boolean ROIGetVolatile( ROI roi )


Return whether the region of interest is volatile or not.

void ROIInsertVertex( ROI roi, Number before, Number


x, Number y )
Insert a vertex with the given coordinates before the indicated vertex of the
region of interest.

Boolean ROIIsClosed( ROI roi )


Returns whether the region of interest is a closed loop or not.

Boolean ROIIsLine( ROI roi )


Return whether the region of interest is a line.

Boolean ROIIsPoint( ROI roi )


Return whether the region of interest is a point.

Boolean ROIIsRange( ROI roi )


Returns whether the region of interest is a range.

Boolean ROIIsRectangle( ROI roi )


Return whether the region of interest is a rectangle.

Boolean ROIIsValid( ROI roi )


Returns 'true' if the region of interest is a valid object.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

282

void ROISetColor( ROI roi, Number r, Number g, Number


b )
Set the color of the region of interest. Each number should be in the range of 0
to 1.

void ROISetDeletable( ROI roi, Boolean deletable )


Sets whether the region of interest should be deletable or not.

void ROISetIsClosed( ROI roi, Boolean is_closed )


Sets whether the region of interest is a closed loop or not (that is the last
vertex connects to the first).

void ROISetLabel( ROI roi, String name )


Set the label on the region of interest.

void ROISetLine( ROI roi, Number sx, Number sy,


Number ex, Number ey )
Set the region of interest to a line with the given start and end coordinates.

void ROISetMoveable( ROI roi, Boolean moveable )


Sets whether the region of interest should be moveable or not.

void ROISetName( ROI roi, String name )


Set the name of the region of interest.

void ROISetPoint( ROI roi, Number x, Number y )


Set the region of interest to a point with the given coordinate.

void ROISetRange( ROI roi, Number start, Number


end )
Sets the region of interest to a range with the given start and end columns.

void ROISetRectangle( ROI roi, Number top, Number


left, Number bottom, Number right )
Set the region of interest to a rectangle with the given coordinates.

void ROISetRegionToValue( ROI roi, ComplexImage mask,


ComplexNumber value, Number top, Number left,
Number bottom, Number right )
Sets the area in 'mask' corresponding to the region to the value 'value'.

void ROISetRegionToValue( ROI roi, RGBImage mask,


RGBNumber value, Number top, Number left, Number
bottom, Number right )
Sets the area in 'mask' corresponding to the region to the value 'value'.

Copyright 2012 Gatan Inc. All Rights Reserved.

283

DigitalMicrograph

void ROISetRegionToValue( ROI roi, ImageReference


mask, Number value, Number top, Number left,
Number bottom, Number right )
Sets the area in 'mask' corresponding to the region to the value 'value'.

void ROISetResizable( ROI roi, Boolean resizable )


Sets whether the region of interest should be resizable or not.

void ROISetVertex( ROI roi, Number index, Number x,


Number y )
Set the coordinates of the given vertex of the region of interest.

void ROISetVolatile( ROI roi, Boolean is_volatile )


Set whether the region of interest is volatile or not.

Related Functions
ROI =( ROI, ! )
Assign a region of interest to a new variable.

ROI =( ROI, ROI )


Assign a region of interest to a new variable.

ROI GetROIFromID( Number id )


Returns the region of interest associated with the ID or NULL if it does not
exist.

ROI ImageDisplayGetROI( ImageDisplay imgDisp, Number


index )
Returns the given ROI on this image display.

ROI ImageDisplayLookupROI( ImageDisplay imgDisp,


String name )
Returns the given ROI on this image display.

ROI ImageDisplayLookupROIByID( ImageDisplay imgDisp,


Number id )
Returns the ROI with the given id on this image display.

ROI NewROI( )
Creates an empty region of interest.

ROI ROINullify( ! )

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

1.8.6

284

Image Operations

Image Operations
Since the DigitalMicrograph scripting language is an interpreted language, is is very slow to
process images by using nested for-loops that access each pixel. This section shows how
you can accomplish the same things by using special image operations.

Pixel by Pixel Operations


A pixel by pixel operation is an image expression where the same operation is applied
at every point. For example, given images a and b of the same size,

a = b + 10
This operation takes the value of every pixel in b, adds 10 to it, and stores the result
into a. Pixel by pixel operations are compiled into machine code to optimize their
speed of execution. Several operations in an image expression may be combined.
This provides a significant performance gain over interpreted expressions. Within a
script, and even on the same line, interpreted expressions may be mixed with
expressions that will be compiled. The compiling is transparent to the script writer
and user. (With the exception that a well written script that uses image expressions
will run much faster than one that uses GetPixel and SetPixel to manipulate every
pixel in an image.)

Number Functions Can Be Used As Image Functions


The most important fact to realize about pixel by pixel operations is that most number
functions can be applied to images. This means, for example, that the tangent
function, tan( realnumber ), may be also used as tan( realimage ).

Intrinsic Variables
Intrinsic variables are predefined variables which take on context sensitive values. All
of the intrinsic variables in the script language pertain specifically to image
expressions. Below is a list:
Name
icol
icolumn
iheight
ipoints
iradius
irow
itheta
iwidth

Copyright 2012 Gatan Inc. All Rights Reserved.

Description
column of the image expression
equivalent to icol
height of the image expression
number of points in the image
expression
distance from the center of the image
expression
row of the image expression
angle with respect to the center of the
image expression
width of the image expression

285

DigitalMicrograph

iplane

plane of the image expression (3D


images)

Some, like ipoints, are constant within an expression for every point evaluated. While
others, like irow, may change at every pixel position in an image expression.

Physical Size
Every image expression must have a physical size before it is evaluated . The
physical size of an image expression is expressed as its width and height.
Usually the physical size of an image expression is the size of images in the
expression.
Intrinsic variables like i col and i r ow do not have an innate size and are context
specific.
Sometimes it is useful to create abstract image expressions that are the result of
mathematical operators applied to the intrinsic variables. However, such image
expressions do not have a physical size and will generate an error if, for example,
assigned to image letters. The function Expr Si ze( ) allows us to give an expression
a physical size. It is defined for real, complex, and RGB image expressions. The
definition for the real version is:

RealImageExpression ExprSize( number width, number


height, RealImageExpression value )
Where width and height are the explicit physical size of the image expression and
value provides the value of the image expression at every point in the image
expression. For example, if there didn't exist an image corresponding to the image
letter a, the short scripts

a = 10
would produce an error. By using ExprSize() we can change this example to make it
work:

a = ExprSize( 256, 256, 10 )


Note: In the preceding example the need to use Expr Si ze( ) could have been
circumvented by creating the images first. However, there are other more
complicated examples which go beyond the scope of this section which definitely
require the use of Expr Si ze( ) .

Whole Image Operations


In general, there are two types of whole image operations - those that result in a new
image, and those that generate a number.
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

286

Some examples of functions that take images and result in numbers are:
Function
sum(a)
product(a)
mean(a)
rms(a)
max(a)
min(a)

Description
sums pixels in image expression
multiplies pixels in image expression
mean of pixels in image expression
root mean square of pixels in image
expression
maximum of pixels in image
expression
minimum of pixels in image expression

Some examples of functions that take images and result in images are:
Function
FFT()
IFFT()
RealFFT()
RealIFFT()
Rotate()

Description
Calculates the complex FFT of a
complex image
Calculates the complex IFFT of a
complex image
Calculates the complex FFT of a real
image
Calculates the real IFFT of a hermitian
complex image
Arbitrarily rotates an image

Whole image operations differ from pixel by pixel operations in that each whole image
operation must be completed before its result can be used. Whole image operations
that result in an image can't be compiled or parallelized with other operations. This
normally is of little concern to the script writer with the exception of possible increased
memory requirements if temporary images have to be created to complete the
specified operations.

Image Subareas
An image subarea is a rectangular sub section of a image.
The Subarea Operator
To create a subarea the subarea operator can be used. The three variations are
(defined as functions):
realsubarea operator[( realimage img, number top, number left, number
bottom, number right )
complexsubarea operator[( compleximage img, number top, number left,
number bottom, number right )
rgbsubarea operator[( rgbimage img, number top, number left, number
bottom, number right )

Copyright 2012 Gatan Inc. All Rights Reserved.

287

DigitalMicrograph

The argument img is the image that the subarea refers to. The arguments top, left,
bottom, and right define the rectangular sub section of that image. Note that bottom
and right are noninclusive. For example, given an image a (256 x 256) and image b
(1024 x 1024),

a = b[ 0, 0, 256, 256 ]
This copies a 256 x 256 square area of pixels from b into a.
The subarea operator may be applied to image expressions. For example, given
image a (128 x 128), images b and c (both 256 x 256),

a = (b + c)[ 0, 0, 128, 128 ]


This
1.
2.
3.
4.

script does the following steps:


Creates a temporary image the size of b and c.
Assigns the result of the expression b + c to the temporary image.
Assigns the subarea [0,0,128,128] of the temporary image to a.
Deletes the temporary image.

The previous example was intended as an example and not the most efficient method
of accomplishing the end effect. It should be rewritten as:

a = b[ 0, 0, 128, 128 ] + c[ 0, 0, 128, 128 ]


This is more efficient because the addition operation is only done on 128 x 128 pixels
as opposed to 256 x 256 pixels.

Setting Subareas
The = (assignment by value) operator is defined for assignment of image expression
to image subareas. For example, given image a,

a[ 0, 1, 20, 30 ] = 0
This would set all of the pixels in the rectangular area of a, with the top/left corner at
(x=1,y=0) and bottom/right corner to (x=30,y=20), to the value 0.

Subarea Variables
Image subarea variables can be declared in a similar ease to image variables. For
example,

subarea center
complexsubarea xyz
rgbsubarea abc
To set a subarea variable use the := (assignment by reference) operator. For
example, given the image a,
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

288

subarea portion := a[ 20, 20, 40, 40 ]


This will set the portion subarea variable to refer to the subsection [20,20,40,40] of a.
Now if portion is used in an image expression it will be equivalent to a[ 20, 20, 40,
40 ]. For example, given image b (20 x 20),

portion = b
This sets the value of the pixels in the subarea of a, [ 20, 20, 40, 40 ], to values of the
pixels in b.

The Selection As A Subarea


To get the selection on an image as a subarea, one of the following functions can be
used:

realsubarea operator[( realimage img )


complexsubarea operator[( compleximage img )
rgbsubarea operator[( rgbimage img )
For example, given image a (128 x 128) and image b (256 x 256) with the selection
[0,0,128,128],

a = b[]
This sets the values of the pixels in image a to the values of the pixels in the subarea
of b equivalent to the selection. The above example is equivalent to:

a = b[0,0,128,128]
Slices
An image slice is a generalization of an image subarea. It specifies a regular grid of
points in an image, whose only restriction is that each dimension of the slice must be
parallel to a dimension of the containing image. Thus, unlike a subarea, its points may
be noncontiguous in the containing image, each dimension of the slice may be
oriented along any dimension of the containing image, and the order of traversal of a
dimension in the slice may be opposite that of the containing image.
A slice can be specified by a starting point, a slice dimensionality, and for each
dimension, a dimension in the containing image, a length, and a stride. (Implicit in the
starting point is its dimensionality, which may be different from the slice dimensionality
).
The script functions of the form

Copyright 2012 Gatan Inc. All Rights Reserved.

289

DigitalMicrograph

Image *slice<n>( Image *img, long x0, long y0, long


z0
, long d0, long l0, long s0
, ...
, long d<n-1>, long l<n-1>, long
s<n-1> )
specify an n-dimensional slice of the image img, starting at point (x0,y0,z0), and its
dimension i extending along dimension di in img, with length li and stride si. For 1 and
2 dimensional images, y0 and z0 should be set to 0, and for 4 and higher dimensional
images, the unspecified starting coordinates are 0.
You can also handle slices as objects. The function

ScriptObject NewImageDataSlice( ulong pn, ulong sn


, long p0, long p1, ..., long p<pn1>
, d0, l0, s0
, ...
, d<sn-1>, l<sn-1>, s<sn-1> )
Creates a slice object that starts at position (p0,p1,...,p<pn-1>), has dimensionality
sn, and for slice dimension i, has source image dimension di, length li, and stride si.
Note that the number of arguments must be exactly 2 + pn + sn*3. This slice may be
applied to an image using either the slice function

Image *slice( Image *src_img, ScriptObject


img_slice )
or the bracket operator

Image *operator[( Image *src_img, ScriptObject


img_slice )
The image slice object has the following interface

class ImageDataSlice
{
ScriptObject GetImageDataSize( ScriptObject self );
ulong
GetNumDimensions( ScriptObject self );
void
SetNumDimensions( ScriptObject self,
ulong sn );
ulong
GetDimensionStartIndex( ScriptObject
self, ulong i );
void
SetDimensionStartIndex( ScriptObject
self, ulong i, ulong start_index );

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

290

void

GetDimensionSlice( ScriptObject self,


ulong i, ulong *di, ulong *li, long *si );
void
SetDimensionSlice( ScriptObject self,
ulong i, ulong di, ulong li, long si );
void
GetParametersV( ScriptObject self, ulong
des_pn, ulong des_sn
, ulong *act_pn, ulong *act_sn
, long *p0, long *p1, ..., long
*p<des_pn-1>
, long *d0, long *l0, long *s0
, ...
, long *d<des_sn-1>, long *l<des_sn1>, long *s<des_sn-1> );
void
SetParametersV( ScriptObject self, ulong
des_pn, ulong des_sn
, long p0, long p1, ..., long
p<des_pn-1>
, long d0, long l0, long s0
, ...
, long d<des_sn-1>, long l<des_sn1>, long s<des_sn-1> );
}
Note that all slice functions that return a slice from an image return an l-value, so any
operation that changes the data of the returned image will also change the data in the
original image.

Examples
Assume we have a 3 dimensional image src_img with dimensions x_len, y_len, and
z_len
To extract a slice at location (x,y) that extends along the z axis, one would use

slice1( src_img, x, y, 0, 2, z_len 1 )


To extract the plane at depth z, one would use

slice2( src_img, 0, 0, z, 0, x_len, 1, 1, y_len, 1


)
To extract a plane whose first dimension is in the y direction but in the opposite
direction as in src_img, and whose second is in the z direction, one would use

slice2( src_img, x, y_len-1, 0, 1, y_len, -1, 2,


z_len, 1 )

Copyright 2012 Gatan Inc. All Rights Reserved.

291

1.8.7

DigitalMicrograph

Packages

Packages
This chapter covers the ability to group scripts together and place them into an automatically
loaded module.

Module and Uses Declarations


In order to control the loading order of the packages placed in any of the package
folders [Core, Packages, Plug-ins], you can specify dependencies through a simple
mechanism.
To declare that a script is part of a particular module, put a line like the following into
your script:

module com.gatan.dm.dialogs
To declare that a script requires another module, put a line like the following into your
script:

uses com.gatan.dm.dialog_handler
Any particular script can only have a single module declaration but may have as many
uses declarations as are necessary.
The module and uses declarations are only handled on a per-package basis. This
means that the package author is responsible for making sure that the scripts within
the package load in the proper order.
When packages are loaded, all scripts within the package combine to form a list of
modules defined in that package. Other packages that require a particular module
from a given package will cause the entire package containing that module to be
loaded. Furthermore, a particular package will not be loaded unless packages
containing all modules listed in the particular package's uses list can be loaded first.
The user should be aware that circular references are not allowed. This means that if
package A requires package B, package B cannot require package A. Both packages
will fail to load in this case.

1.8.8

File Input and Output

File Input and Output


There are several API's for accessing external files from DigitalMicrograph. A file is ideally
thought of as a stream and some of the functions below describe accessing a stream. A
stream may be based on a file or some other stream of data such as a memory buffer or
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

292

data from a tag.

Path Construction Functions


DigitalMicrograph provides several functions to determine directories and construct
path and file names.
Functions to Get Predefined Directories

string GetApplicationDirectory( number index, number


create_if_necessary )
Returns the path associated with the directory given by the index. See the
table below for a list of valid index values. The create_if_necessary parameter
indicates whether the directory should be created if it doesn't already exist.

string GetApplicationDirectory( string dir_name,


number create_if_necessary )
Returns the path associated with the directory given by the directory name
parameter. See the table below for a list of valid directory names. The
create_if_necessary parameter indicates whether the directory should be
created if it doesn't already exist.

number GetApplicationDirectory( string dir_name,


number create_if_necessary, string &dir_path_out
)
Stores the path associated with the directory given by the directory name
parameter in the dir_path_out parameter. It returns 1 or 0 to indicate whether
the directory exists. The create_if_necessary parameter indicates whether the
directory should be created if it doesn't already exist.

void SetApplicationDirectory( string dir_name, number


create_if_necessary, string dir_path )
Overrides the built-in values for the directory indicated by dir_name to dir_path.
The create_if_necessary parameter indicates whether the directory should be
created if it doesn't already exist.
Name
application

Index
1000

preference

1004

plugin

1008

color_table

1012

core

1016

Copyright 2012 Gatan Inc. All Rights Reserved.

Description
The application's
directory.
The directory where the
preference file is
located.
The directory where
plug-ins are located.
The directory where the
color table images are
located.
The directory where the
core script plug-ins are
located.

293

DigitalMicrograph

reference_image

1020

auto_save

1100

current
executable

0
1

open_save

temporary
system

3
4

The directory where


reference images are
located.
The directory where
images are autosaved.
The current directory.
The directory where the
executable is located.
The directory that
appears when the user
opens an open or save
dialog.
A temporary directory.
The system directory.

Functions to Manipulate Path Strings


string PathConcatenate( string initial_path, string
final_path )
concatenates the partial path final_path to the existing path initial_path.

string PathBeginRelative()
returns a starting point for a relative path.

string PathAddParentIndirection( string path )


returns a path referring to the parent of path.

string PathGetFullpath( string path )


returns the absolute path for the given relative path.

string PathExtractDirectory( string path, number


path_type )
returns the directory portion of the given path according to the path_type
parameter. The path_type variable should be 0.

string PathExtractFileName( string path, number


path_type )
returns the file name portion of the given path according to the path_type
parameter. The path_type variable should be 0.

string PathExtractBaseName( string path, number


path_type )
returns the file name without the extension portion of the given path according
to the path_type parameter. The path_type variable should be 0.

string PathExtractExtension( string path, number


path_type )

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

294

returns the file name extension portion of the given path according to the
path_type parameter. The path_type variable should be 0.

string PathExtractParentDirectory( string path,


number path_type )
function returns the parent directory portion of the given path according to the
path_type parameter.The path_type variable should be 0.

Stream Object
The following object can be used to access a low level stream.

class Stream
{
number StreamGetSize( object self )
returns the size of the stream in bytes.

number StreamGetPos( object self )


returns the current stream position.

void StreamSetSize( object self, number size )


sets the size of the stream for writable streams. It is an error to invoke this
function on read-only streams.

void StreamSetPos( object self, number base, number


offset )
sets the current position in the stream. The base parameter determines what
the offset is relative to. Pass 0 for beginning of stream; pass 1 for current
position, pass 2 for end of stream

string StreamReadAsText( object self, number


encoding, number count )
reads a line of text ending in a end of line character. You must pass the text
encoding you expect to read. The resulting string is stored in the str_out
parameter.

number StreamReadTextLine( object self, number


encoding, string &str_out )
void StreamWriteAsText( object self, number encoding,
string str )
writes text to the stream. You must add the end of line character yourself. You
must pass the text encoding in which the text will be written.

}
You can create a stream object with the following functions.

Copyright 2012 Gatan Inc. All Rights Reserved.

295

DigitalMicrograph

object NewStreamFromFileReference( number


file_reference, number do_close )
Takes a file reference and can automatically close the file reference when the
resulting object goes out of scope.

object NewStreamFromBuffer( object memory_buffer )


Creates a stream from a memory buffer.

Streaming Raw Data


The following functions can be used to read raw data from a stream.

void ImageReadImageDataFromStream( image image,


object stream, number stream_byte_order )
void ImageWriteImageDataToStream( Image *image,
ScriptObject stream, ulong stream_byte_order )
void TagGroupReadIndexedTagDataFromStream( TagGroup
tagGroup, ulong index, ScriptObject stream,
ulong stream_byte_order )
void TagGroupReadTagDataFromStream( TagGroup
tagGroup, string tag_path, ScriptObject stream,
ulong stream_byte_order )
void TagGroupWriteIndexedTagDataToStream( TagGroup
tagGroup, ulong index, ScriptObject stream,
ulong stream_byte_order )
void TagGroupWriteTagDataToStream( TagGroup tagGroup,
string tag_path, ScriptObject stream, ulong
stream_byte_order )
In each of the above functions, stream refers to a stream object from which the data
is to be read or to which it will be written, and stream_byte_order describes the byte
ordering of the data in the stream. Each function will read or write the specified data
from or to the stream, using the specified byte order, and update the stream's position
to point just after the data transferred.
The functions beginning with Image will transfer the data in the image ( just the data,
not any type or size information ) between the passed in image and stream. The
layout within the stream is row-major, with the element format is determined by the
image data type.
The functions beginning with TagGroup will transfer the contents of a single tag to or
from the stream. The tag is relative to the tag group tagGroup, and can either be
specified by a tag path, as the parameter String tag_path, or by index, as the
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

296

parameter ulong index. The specific type of the tag determines the format with which
the data will be transferred between the tag and the stream. For example, to stream
out two 32-bit unsigned integers, followed by a 32-bit signed integer, and then two 16bit unsigned integers, use the script

Object stream = NewStreamFromBuffer


( NewMemoryBuffer( 256 ) )
TagGroup tg = NewTagGroup();
Number stream_byte_order = 1; // 1 == bigendian, 2
== littleendian
Number v_uint32_0, v_uint32_1, v_sint32_0,
v_uint16_0, v_uint16_1
// Create the tags and initialize with
values
tg.TagGroupSetTagAsUInt32( "UInt32_0",
tg.TagGroupSetTagAsUInt32( "UInt32_1",
tg.TagGroupSetTagAsLong( "SInt32_0", 0
tg.TagGroupSetTagAsUInt16( "UInt16_0",
tg.TagGroupSetTagAsUInt16( "UInt16_1",
// Stream the data into the tags
TagGroupReadTagDataFromStream( tg,
stream, stream_byte_order );
TagGroupReadTagDataFromStream( tg,
stream, stream_byte_order );
TagGroupReadTagDataFromStream( tg,
stream, stream_byte_order );
TagGroupReadTagDataFromStream( tg,
stream, stream_byte_order );
TagGroupReadTagDataFromStream( tg,
stream, stream_byte_order );

default
0
0
)
0
0

)
)
)
)

"UInt32_0",
"UInt32_1",
"SInt32_0",
"UInt16_0",
"UInt16_1",

// Get the data from the tags


tg.TagGroupGetTagAsUInt32( "UInt32_0", v_uint32_0
tg.TagGroupGetTagAsUInt32( "UInt32_1", v_uint32_1
tg.TagGroupGetTagAsLong( "Sint32_0", v_sint32_0 )
tg.TagGroupGetTagAsUInt16( "UInt16_0", v_uint16_0
tg.TagGroupGetTagAsUInt16( "UInt16_1", v_uint16_1
The stream byte order parameter can take one of the following values.
Byte Order Value
0
1

Copyright 2012 Gatan Inc. All Rights Reserved.

Explanation
Default byte order of the current
platform
Big-endian byte order

)
)
)
)

297

DigitalMicrograph

Little-endian byte order

Low Level API


The following functions can be used to access the low-level API. The user must take
special care to close the file when they are finished.
Functions for Opening and Closing Files

number OpenFileForReading( string file_name )


opens the given file for reading. The file can be an absolute or relative path
followed by a file name with an extension. The file reference for the file is
returned.

number OpenFileForReadingAndWriting( string file_name


)
opens the given file for reading and writing. The file can be an absolute or
relative path followed by a file name with an extension. The file reference for
the file is returned.

number OpenFileForWriting( string file_name )


opens the given file for writing. The file can be an absolute or relative path
followed by a file name with an extension. The file reference for the file is
returned.

void CloseFile( number file_ref )


closes the file with the given file reference.
Functions for Creating Files

void CreateFile( string file_name )


creates a file at the given absolute or relative path specified by file_name.

number CreateFileForWriting( string file_name )


creates a file at the given absolute or relative path specified by file_name and
opens it for writing. It returns the file reference.
Functions for Reading and Writing to Files

string ReadFile( number file_ref, long count )


reads count bytes from the given file and returns the result as a string. The
function will read any bytes (they don't have to be a string) but the caller will
have to access the string specially if the read bytes include null bytes. The
string is assumed to be in the local encoding.

number ReadFileLine( number file_ref, string


*string )
reads a line from the given file. A line ends at the first end of line character
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

298

(0xD, 0xA, 0x0). The resulting string is assumed to be encoded in the local
encoding and is returned in the parameter string. The result of the function is 1
to indicate it succeeded and 0 to indicate it failed.

void WriteFile( number file_ref, string data )


writes the string to the given file. The string is assumed to be in the local
encoding.

string ReadFile( number file_ref, number encoding,


number count )
reads a string with the given length in the given encoding.

number ReadFileLine( number file_ref, number


encoding, string *string )
reads a line from the given file. A line ends at the first end of line character as
defined in the encoding. The result of the function is 1 to indicate it succeeded
and 0 to indicate it failed.

void WriteFile( number file_ref, number encoding,


string data )
writes the string to the given file in the given encoding.
Miscellaneous Functions

void DeleteImageFile( string file_name )


delete the file with the given file_name.

void DeleteFile( string file_name )


delete the file with the given file_name.

void CreateDirectory( string directory_name )


creates a directory with the given directory_name.

void DeleteDirectory( string directory_name )


deletes the directory with the given directory_name.

bool DoesFileExist( string directory_name )


returns whether the given file exists.

bool DoesDirectoryExist( string directory_name )


returns whether the given directory exists.

TagGroup GetFilesInDirectory( string directory_name,


number search_flags )
returns a list of string tags with the files in directory_name. The search_flags
parameter can be a 1 to include only files; 2 to include only directories; or 3 to
include both files and directories.

Copyright 2012 Gatan Inc. All Rights Reserved.

299

DigitalMicrograph

Memory Buffers
The memory buffer represents a range of memory. The following function can
be used to create memory buffer objects.

object NewMemoryBuffer( number initial_size )


creates a memory buffer with the given initial size.

Text Encoding

1.8.9

Value
0

Name
local encoding

western encoding

unicode encoding

Explanation
Local character set.
Determined by settings in
Windows.
DigitalMicrograph (US)
character set.
Unicode character set.

Utility Functions

Utility Functions
Timing
DigitalMicrograph provides access to tick-based timers at two resolutions, low and
high. Each timer is implemented on top of an internal tick count that is periodically
updated to reflect the time passed since some reference point, with each count
indicating an elapsed time of tick_unit seconds.

Number GetOSTickCount()
Returns the current tick count.

Number GetHighResTickCount()
Returns the current high resolution tick count.

Number GetOSTicksPerSecond()
Returns the number of tick units in one second, which is 1000.

Number GetHighResTicksPerSecond()
Returns the number of high res tick units in one second.

Number CalcOSSecondsBetween( Number tick_0, Number


tick_1 )
Returns the time in seconds indicated by the tick range [tick_0,tick_1) if tick_0
occurred before tick_1, and negative the time in seconds indicated by the
range [tick_1,tick_0) otherwise.

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

300

double CalcHighResSecondsBetween( Number tick_0,


Number tick_1 )
Returns the time in seconds indicated by the tick range [tick_0,tick_1) if tick_0
occurred before tick_1, and negative the time in seconds indicated by the
range [tick_1,tick_0) otherwise.

Number GetOSTickResolution()
Number GetHighResTickResolution()
Even though the elapsed time is reported with a resolution of tick_unit
seconds, the timer might not actually update the tick count with that frequency.
This function returns an estimate of the minimum number of ticks between
two unequal tick counts returned by GetOSTickCount() and
GetHighResTickCOunt()

Date/Time
DigitalMicrograph provides a set of utility functions that manipulate a date represented
as a 64-bit signed integer which represents a number of time units of duration
date_time_unit seconds past a reference date reference_date. Both date_time_unit
and reference_unit are platform dependent, but routines are provided for converting
between dates with differing time units and reference dates, and more specialized
routines are provided for converting to and from the long value Java typically uses for
specifying dates and times, milliseconds since January 1, 1970, 00:00:00 GMT. Note
that these functions are only as accurate as the clock implemented by the underlying
system.

Number GetCurrentTime()
Returns the number representing the current date and time.

Number GetUnixEpochTime()
Returns the number representing the date and time January 1, 1970, 00:00:00
GMT.

Number CalcTimeUnitsBetween( Number time_1, Number


time_2, Number time_units_per_second )
Calculates the time between time_1 and time_2 in terms of units of duration
time_units_per_second. Thus, to determine the number of milliseconds
between time_1 and time_2, use CalcTimeUnitsBetween( time_1, time_2,
1000.0 ). This function can be used to convert from the platform time
representation to an alternate representation. For example, to convert to
milliseconds since the Unix epoch, one can use CalcTimeUnitsBetween
( GetUnixEpochTime(), time, 1000.0 ).

Number AddTimeUnitsToTime( Number time, Number


time_units, Number time_units_per_second )
Modifies a time by adding time_units increments of duration
time_units_per_second. This function can be used to convert from an
alternate time representation to the platform representation. For example, to
Copyright 2012 Gatan Inc. All Rights Reserved.

301

DigitalMicrograph

convert from milliseconds since the Unix epoch to the platform time, one can
use AddTimeUnitsToTime( GetUnixEpochTime(), time, 1000.0 ).
Utility functions are provided to convert between calendar dates and time for
two calendars, Universal Coordinated Time and the proleptic Gregorian
Calendar in the system's current time zone. The date is represented as year,
month, day, hour, minute, second, and nanoseconds, and the conversion
functions come in two forms, the construct function which converts a calendar
date to a time, and a deconstruct function that converts a time to a calendar
date. These functions rely on platform functions to implement the conversion,
so any limits in the underlying implementation are exposed in these functions,
but dates in the 20th and 21st centuries are ok. The function prototypes are
listed below.

Number ConstructLocalGregorianDate( Number year,


Number month, Number day, Number hour, Number
minute, Number second, Number nanosecond )
void DeconstructLocalGregorianDate( Number time,
Number *year, Number *month, Number *day, Number
*hour, Number *minute, Number *second, Number
*nanosecond )
Number ConstructUTCDate( Number year, Number month,
Number day, Number hour, Number minute, Number
second, Number nanosecond )
void DeconstructUTCDate( Number time, Number *year,
Number *month, Number *day, Number *hour, Number
*minute, Number *second, Number *nanosecond )
A time can be formatted as a string representing a localized date in the current
time zone using the function

String FormatTimeString( Number time, Number format )


The parameter format specifies how the time will be formatted. Bits 0-3
encode a value that specifies the format for the date, and bits 4-7 encode a
value that specifies the format for the time. The currently allowed date values
are 0 if the date is not included, 1 for a short representation that specifies the
month as a number, 2 for a format that specifies the month and day of the
week as strings, and 3 for a format that specifies the month and day of week
as abbreviated strings. The currently allowed time values are 0 if the time is
not to be included, 1 to specify the time without a seconds specifier, and 2 to
specify a time with a seconds specifier.
See the following sript for an example:

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

302

Number time = ConstructLocalGregorianDate( 2003,


12, 13, 11, 27, 30, 0 )
number dateFormat = 2
number timeFormat = 2
number format = dateFormat + 16 * timeFormat
Result( FormatTimeString( time, format ) +
"\n" )
1.8.10 Example Scripts

Example scripts
Tag Types explores how different tag types are encoded.
1.8.10.1 Tag Types

Tag Types
Description
Tags have a type. This script adds tags of all different typtes to a TagGroup and then
printsout the contents of the TagGroup. This shows how all the tagTypes are
encoded.

Script Code
TagGroup tg = NewTagGroup()
number index
index = tg.TagGroupCreateNewLabeledTag( "Array" )
tg.TagGroupSetIndexedTagAsArray( index,
CreateFloatImage("temp", 512, 512) )
index = tg.TagGroupCreateNewLabeledTag( "Boolean" )
tg.TagGroupSetIndexedTagAsBoolean( index, 1 )
index = tg.TagGroupCreateNewLabeledTag( "Double" )
tg.TagGroupSetIndexedTagAsDouble( index, 4.5678 )
index = tg.TagGroupCreateNewLabeledTag( "Complex" )
tg.TagGroupSetIndexedTagAsDoubleComplex( index, complex
( 0.5, 0.7 ) )
index = tg.TagGroupCreateNewLabeledTag( "RGB" )
tg.TagGroupSetIndexedTagAsEightBitColor( index, rgb
( 255, 0, 0) )
index = tg.TagGroupCreateNewLabeledTag( "Float" )
Copyright 2012 Gatan Inc. All Rights Reserved.

303

DigitalMicrograph

tg.TagGroupSetIndexedTagAsFloat( index, 4.567 )


index = tg.TagGroupCreateNewLabeledTag
( "FloatComplex" )
tg.TagGroupSetIndexedTagAsFloatComplex( index, complex
( 0.7, 0.8 ) )
index = tg.TagGroupCreateNewLabeledTag( "FloatPoint" )
tg.TagGroupSetIndexedTagAsFloatPoint( index, 0.5,
0.6 )
index = tg.TagGroupCreateNewLabeledTag( "FloatRect" )
tg.TagGroupSetIndexedTagAsFloatRect( index, 0, 0, 512,
512 )
index = tg.TagGroupCreateNewLabeledTag( "Long" )
tg.TagGroupSetIndexedTagAsLong( index, 5933 )
index = tg.TagGroupCreateNewLabeledTag( "LongPoint" )
tg.TagGroupSetIndexedTagAsLongPoint( index, 5933,
6789 )
index = tg.TagGroupCreateNewLabeledTag( "LongRect" )
tg.TagGroupSetIndexedTagAsLongRect( index, 0, 0, 4096,
4096 )
index = tg.TagGroupCreateNewLabeledTag( "RGBNumber" )
tg.TagGroupSetIndexedTagAsNumber( index, rgb( 100, 200,
255) )
index = tg.TagGroupCreateNewLabeledTag( "ComplexNumber"
)
tg.TagGroupSetIndexedTagAsNumber( index, complex( 1,
1 ) )
index = tg.TagGroupCreateNewLabeledTag( "Number" )
tg.TagGroupSetIndexedTagAsNumber( index, 5933 )
index = tg.TagGroupCreateNewLabeledTag( "RGBUInt16" )
tg.TagGroupSetIndexedTagAsRGBUInt16( index, 100, 89, 45
)
index = tg.TagGroupCreateNewLabeledTag( "Short" )
tg.TagGroupSetIndexedTagAsShort( index, 5933 )
index = tg.TagGroupCreateNewLabeledTag( "ShortPoint" )
tg.TagGroupSetIndexedTagAsShortPoint( index, 10, 20)
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

304

index = tg.TagGroupCreateNewLabeledTag( "ShortRect" )


tg.TagGroupSetIndexedTagAsShortRect( index, 0, 0, 100,
100 )
index = tg.TagGroupCreateNewLabeledTag( "String" )
tg.TagGroupSetIndexedTagAsString( index, "Very long
script" )
index = tg.TagGroupCreateNewLabeledTag( "TagGroup" )
tg.TagGroupSetIndexedTagAsTagGroup( index, NewTagGroup
() )
index = tg.TagGroupCreateNewLabeledTag( "Text" )
tg.TagGroupSetIndexedTagAsText( index, "Still more
text" )
index = tg.TagGroupCreateNewLabeledTag( "UInt16" )
tg.TagGroupSetIndexedTagAsUInt16( index, 5 )
index = tg.TagGroupCreateNewLabeledTag( "UInt32" )
tg.TagGroupSetIndexedTagAsUInt32( index, 67 )
number count = tg.TagGroupCountTags( )
number i
for( i = 0; i < count; ++i )
{
String label = tg.TagGroupGetTagLabel( i )
number type0 = tg.TagGroupGetTagType( i, 0 )
number type1 = tg.TagGroupGetTagType( i, 1 )
number type2 = tg.TagGroupGetTagType( i, 2 )
// more information is available for some tagTypes
Result( type0 + "\t : "+ type1 + "\t : "+ type2 + "\t
: " + label + "\n" )
}

Discussion
The above script generate the following output:

20
8
15
15
7
6

6
0
0
0
0
0

Copyright 2012 Gatan Inc. All Rights Reserved.

262144
Array
0
Boolean
2
Complex
2
ComplexNumber
0
Double
0
Float

305

DigitalMicrograph

15
15
15
3
15
15
7
3
3
15
2
15
15
20
0
20
4
5

0
0
0
0
0
0
0
0
0
0
0
0
0
4
0
4
0
0

2
2
4
0
2
4
0
0
0
3
0
2
4
16
0
15
0
0

FloatComplex
FloatPoint
FloatRect
Long
LongPoint
LongRect
Number
RGB
RGBNumber
RGBUInt16
Short
ShortPoint
ShortRect
String
TagGroup
Text
UInt16
UInt32

From this output one can deduce the following type info:
0 TagGroup
2 Short
3 RGB or Long (both contain 4 bytes)
4 UInt16 (unsigned short)
5 UInt32 (unsigned long)
6 Float
7 Number or Double
8 Boolean
15 Any multiItem field. In this case the third column takes on
2 Complex, FloatComplex, FloatPoint, LongPoint or ShortPoint
3 RGBUInt16
4 FloatRect or ShortRect
(Showing more field from the TagType allows differentation among all the
types)
20 Array type, where second column shows datatype and third column
number of items

1.8.11 Reference
1.8.11.1 Script Functions By Category

Script Functions By Category


This section contains a list of all the basic functions not explicitly documented in the rest of
the manual. Most of the functions do not include the parameters to use. To find out what the
signature is of a function you want to use, type it with an open and close bracket in a script
window and run the script. If the function requires any parameters the complete function
signature will appear in the results window.
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

306

Real Numbers
Operators
Functions
Complex Numbers
Operators
Functions
RGB Numbers
Operators
Functions
Real Images
Complex Images
RGB Images
Image Data Types
Image Management
Image Processing
Image Display
Image Selections
Image Scrap
Annotations
Persistent Notes
Image Notes
Annotation Notes
Strings
Operators
Functions
Number Conversion
Input/Output
Dialogs
Miscellaneous

Real Numbers
Operators
Name
!
!=
&&
*
**
*=
+
++

Copyright 2012 Gatan Inc. All Rights Reserved.

Summary
Logical NOT operator for a real
number
Inequality operator for real numbers
Logical AND operator for real numbers
Multiply operator for real numbers
Exponentation operator for real
numbers
Multiply and assign operator for real
numbers
Addition operator for real numbers
Increment operator for a real number

307

DigitalMicrograph

+=
--=
/
/=
<
<=
=
==
>
>=
?
||

Add and assign operator for real


numbers
Negation operator for a real number
Subtraction operator for real numbers
Decrement operator for real numbers
Subtract and assign operator for real
numbers
Division operator for real numbers
Divide and assign operator for real
numbers
Less than operator for real numbers
Less than or equal operator for real
numbers
Assignment operator for real numbers
Equality operator for real numbers
Greater than operator for real numbers
Greater than or equal operator for real
numbers
Arithmetic if operator for real numbers
Logical OR operator for real numbers

Functions
Name
abs
acos
AiryAi
AiryBi
asin
atan
atan2
atanh
BesselI
BesselJ
BesselK
BesselY
Beta
BinomialCoefficient
BinomialRandom

Summary
Calculates absolute value of a real
number
Calculates the arccosine of a real
number
Calculates the Airy Ai function
Calculates the Airy Bi function
Calculates the arcsine of a real
number
Calculates the arctangent of a real
number
Calculates the arctangent of y/x for
real numbers
Calculates the hyperbolic arctangent of
a real number
Calculates the general Bessel I
function
Calculates the general Bessel J
function
Calculates the general Bessel K
function
Calculates the general Bessel Y
function
Calculates the beta function
Calculates the binomial coefficient
Calculates a random number with
binomial distribution
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

clip
cos
cosh
distance
erf
erfc
exp
exp1
exp10
exp2
ExponentialRandom
Factorial
Gamma
GammaP

308

Clip real number to be in a range


Calculates the cosine of a real number
Calculates the hyperbolic cosine of a
real number
Calculates the pythagorean theorem
Calculates the error function
Calculates the complement of the
error function
Calculates the exponential of a real
number
Calculates the exponential - 1 of a real
number
Calculates 10 raised to a real number
Calculates 2 raised to a real number
Calculates a random number with
exponential distribution
Calculates the factorial of a real
number
Calculates the gamma of a real
number
Calculates the incomplete gamma
function

Complex Numbers
Operators
Name
!=
*
**
+
/
=
==
?

Summary
Inequality operator for complex
numbers
Multiply operator for complex numbers
Exponentation operator for complex
numbers
Addition operator for complex numbers
Negation operator for a complex
number
Subtraction operator for complex
numbers
Division operator for complex numbers
Assignment operator for complex
numbers
Equality operator for complex numbers
Arithmetic operator for complex
numbers

Functions
Name
abs
Copyright 2012 Gatan Inc. All Rights Reserved.

Summary
Calculates the absolute value of a

309

DigitalMicrograph

cis
complex
conjugate
cos
cosh
exp
imaginary
log
modulus
norm
Phase
Polar
real
Rect
sin
sinh
sqrt
tan
tanh

complex number
Calculates a unit vector in the complex
plane
Creates a complex number from two
real numbers
Calculates the conjugate of a complex
number
Calculates the cosine of a complex
number
Calculates the hyperbolic cosine of a
complex number
Calculates the exponential of a
complex number
Returns the imaginary portion of a
complex number as a real number
Calculates the logarithm of a complex
number
Calculates the modulus of a complex
number
Calculates the norm of a complex
number
Calculates the phase of a complex
number
Calculates the polar representation of
a rectangular complex number
Returns the real portion of a complex
number
Calculates the rectangular
representation of a polar complex
number
Calculates the sine of a complex
number
Calculates the hyperbolic sine of a
complex number
Calculates the square root of a
complex number
Calculates the tangent of a complex
number
Calculates the hyperbolic tangent of a
complex number

RGB Numbers
Operators
Name
!=
*
+

Summary
Inequality operator for RGB numbers
Multiply operator for RGB numbers
Addition operator for RGB numbers
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

/
=
==
?

310

Subtraction operator for RGB numbers


Negation operator for a RGB number
Division operator for RGB numbers
Assignment operator for RGB
numbers
Equality operator for RGB numbers
Arithmetic if operator for RGB
numbers

Functions
Name
alpha
blue
green
red
rgb
rgba

Summary
Returns the alpha portion of an RGB
number as a real number
Returns the blue portion of an RGB
number as a real number
Returns the green portion of an RGB
number as a real number
Returns the red portion of an RGB
number as a real number
Creates an RGB number from the real
number arguments
Creates an RGB number from the real
number arguments

Real Images
Name
DotProduct
ExprSize
ExprSize
max
max
mean
MeanSquare
min
min
Polynomial
Copyright 2012 Gatan Inc. All Rights Reserved.

Summary
Calculates the dot product of two real
image expressions
Sets the physical size of a real image
expression
Sets the physical size of a real image
expression
Finds the maximum of a real image
expression
Finds the maximum value and position
for a real image expression
Calculates the mean of a real image
expression
Calculates the mean square of a real
image expression
Finds the minimum value and position
for a real image expression
Finds the minimum of a real image
expression
Calculates a polynomial expansion

311

DigitalMicrograph

product
RMS
sum
TimeBar
Warp

using a real image expression


Calculates the product of a real image
expression
Calculates the RMS of a real image
expression
Calculates the sum of a real image
expression
Displays a timebar while evaluating
real image expression
Calculates bilinear interpolated value
within a real image

Complex Images
Name
DotProduct
ExprSize
ExprSize
Polynomial
product
sum
TimeBar
Warp

Summary
Calculates the dot product of two
complex image expressions
Sets the physical size of a complex
image expression
Sets the physical size of a complex
image expression
Calculates a polynomial expansion
using a complex image expression
Calculates the product of a complex
image expression
Calculates the sum of a complex
image expression
Displays a timebar while evaluating
complex image expression
Calculates bilinear interpolated value
within a complex image

RGB Images
Name
ExprSize
ExprSize
TimeBar
Warp

Summary
Sets the physical size of an RGB
image expression
Sets the physical size of an RGB
image expression
Displays a timebar while evaluating
RGB image expression
Calculates bilinear interpolated value
within a RGB image

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

312

Image Data Types


Name
ComplexImage
IntegerImage
IsComplexDataType
IsIntegerDataType
IsRealDataType
IsRGBDataType
RealImage
RGBImage

Summary
Creates a complex image
Creates an integer image
Checks if an image is a complex data
type
Checks if an image is an integer data
type
Checks if an image is a real data type
Checks if an image is an RGB data
type
Creates a real image
Creates an RGB image

Image Management
Name
ClearImage
CloseImage
CreateImageFromDisplay
DeleteImage
DoesImageExist
Get2DSize
GetFrontImage
GetFrontImage
GetImageDataSeed
GetImageFromID
GetImageFromID
GetImageID
GetLabel
GetName
GetNamedImage
GetNamedImage
GetSize
KeepImage
OpenImage
PrintImage
SaveImage
SetName

Copyright 2012 Gatan Inc. All Rights Reserved.

Summary
Clear an image
Close an image
Creates a display representation of an
image
Delete an image
Checks if an image exists
Get the size of an image
Gets the front image
Gets the front image
Gets an image's data seed
Gets image from an ID
Gets image from an ID, returns false if
none
Gets an image's ID
Gets the image letter of an image
Gets the name of an image
Get an image from a name
Get an image from a name, returns
false if none
Get the size of an image
Retains an image
Opens an image file
Prints an image
Saves an image
Sets the name of an image

313

DigitalMicrograph

Image Processing
Name
AnalyzeDiffractogram
AutoCorrelation
CrossCorrelation
CrossProduct
FFT
FlipHorizontal
FlipVertical
GetPixel
IFFT
MatrixDeterminant
MatrixInverse
MatrixMultiply
MatrixPrint
MatrixTranspose
MedianFilter
RealFFT
RealIFFT
Reduce
ReducedFFT
Rotate
RotateLeft
RotateRight
SetPixel
ShiftCenter
SwapByteOrder
SwapWordOrder
variance

Summary
Analyzes a diffractogram
Calculates the cross correlation of a
real image
Calculates the cross correlation of two
real images
Calculates the cross product
Calculates the complex FFT of a
complex image
Flips an image horizontally
Flips an image vertically
Gets a pixel in a real image
Calculates the complex IFFT of a
complex image
Calculates the matrix determinant of a
real image
Calculates the matrix inverse of a real
image
Calculates the matrix multiplication of
a real image
Prints an image as a matrix
Calculates the matrix transpose of a
real image
Applies a median filter to an image
Calculates the complex FFT of a real
image
Calculates the real IFFT of a hermitian
complex image
Reduces an image by a factor of two
Calculates reduced FFT
Arbitrarily rotates an image
Rotates an image to the left
Rotates an image to the right
Sets a pixel in a real image
Shifts each dimension of an image by
half
Performs a byte swap on each pixel in
an image
Performs a word swap on each pixel in
an image
Calculates the variance of an image

Image Display

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

Name
DisplayAt
GetCLUT
GetOrigin
GetScale
GetWindowPosition
GetWindowSize
HideImage
SetColorMode
SetComplexMode
SetContrastMode
SetCustomCLUT
SetDisplayType
SetImagePositionWithinWindow
SetInversionMode
SetLimits
SetMinContrast
SetOrigin
SetScale
SetSurvey
SetSurveyTechnique
SetWindowPosition
SetWindowSize
SetZoom
ShowImage
UpdateImage

314

Summary
Display image at position
Gets the CLUT of an image
Gets the origin of an image
Gets the scale of an image
Returns position of an image window
Returns the size of an image window
Hides an image
Sets the color mode of an image
Sets the complex mode of an image
Sets the contrast mode of an image
Sets the CLUT of an image
Sets the display type of an image
Sets image position in window
Sets the inversion mode of an image
Sets the contrast limits of an image
Sets the minimum contrast of an
image
Sets the origin of an image
Sets the scale of an image
Sets surveying on or off for an image
Sets the survey technique of an image
Sets the position of an image window
Sets the size of an image window
Sets the zoom of an image
Shows an image
Forces an update of an image

Image Selections
Name
ClearSelection
ExpandSelection
GetSelection
SetSelection

Summary
Removes the selection from an image
Expands the selection of an image
Gets the selection rectangle of an
image
Sets the selection rectangle of an
image

Image Scrap
Name
ScrapClear
ScrapCopy
ScrapGetLocation

Copyright 2012 Gatan Inc. All Rights Reserved.

Summary
Removes the pasted image from an
image
Copies an image selection to the
scrap
Returns the top-left location of the
pasted image's rectangle

315

DigitalMicrograph

ScrapGetSize
ScrapMerge
ScrapPaste
ScrapPasteNew
ScrapSetLocation

Returns the size of the pasted image's


rectangle
Merges the pasted image
Pastes the scrap into an image
Pastes the scrap into a new image
Sets the location of the pasted image
of an image

Annotations
Name
AnnotationType
CountAnnotations
CreateArrowAnnotation
CreateBoxAnnotation
CreateDoubleArrowAnnotation
CreateLineAnnotation
CreateOvalAnnotation
CreateTextAnnotation
DeleteAnnotation
DeselectAnnotation
GetAnnotationRect
GetNthAnnotationID
IsAnnotationSelected
MoveAnnotation
OffsetAnnotation
SelectAnnotation
SetAnnotationBackground
SetAnnotationFace
SetAnnotationFont
SetAnnotationJustification
SetAnnotationRect
SetAnnotationSize
ValidAnnotation

Summary
Returns the type of an annotation
Returns the number of annotations in
an image
Creates an arrow annotation
Creates a box annotation
Creates a double ended arrow
annotation
Creates a line annotation
Creates an oval annotation
Creates a text annotation
Deletes an annotation
Deselects an annotation
Gets the rectangle of the annotation
Get the ID of an annotation
Checks if an annotation is selected
Moves an annotation
Offsets an annotation
Selects an annotation
Sets the background of an annotation
Sets the text face of an annotation
Sets the text font of an annotation
Sets the text justification of an
annotation
Sets the rect of an annotation
Sets the text size of an annotation
Checks if specified annotation exists

Persistent Notes
Name
DeletePersistentNote
GetPersistentComplexNumberNote
GetPersistentNoteState

Summary
Deletes persistent note
Gets the value of a persistent complex
number note
Gets persistent note state

Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

GetPersistentNumberNote
GetPersistentRectNote
GetPersistentRGBNumberNote
GetPersistentStringNote
GetPersistentStringNote
SetPersistentComplexNumberNote
SetPersistentKeywordNote
SetPersistentNoteState
SetPersistentNumberNote
SetPersistentRectNote
SetPersistentRGBNumberNote
SetPersistentStringNote

316

Gets the value of a persistent number


note
Gets the value of a persistent rect note
Gets the value of a persistent RGB
number note
Gets the value of a persistent string
note
Gets the value of a persistent string
note
Sets the value of a persistent complex
number note
Adds a persistent keyword note
Sets persistent note state
Sets the value of a persistent number
note
Sets the value of a persistent rect note
Sets the value of a persistent RGB
number note
Sets the value of a persistent string
note

Image Notes
Name
DeleteNote
GetComplexNumberNote
GetNoteState
GetNumberNote
GetRectNote
GetRGBNumberNote
GetStringNote
GetStringNote
SetComplexNumberNote
SetKeywordNote
SetNoteState
SetNumberNote
SetRectNote
SetRGBNumberNote
SetStringNote

Annotation Notes
Copyright 2012 Gatan Inc. All Rights Reserved.

Summary
Deletes image note
Gets the value of an image complex
number note
Gets image note state
Gets the value of an image number
note
Gets the value of an image rect note
Gets the value of an image RGB
number note
Gets the value of an image string note
Gets the value of an image string note
Sets the value of an image complex
number note
Adds a keyword note to an image
Sets image note state
Sets the value of an image number
note
Sets the value of an image rect note
Sets the value of an image RGB
number note
Sets the value of an image string note

317

DigitalMicrograph

Name
DeleteAnnotationNote
GetAnnotationComplexNumberNote
GetAnnotationNoteState
GetAnnotationNumberNote
GetAnnotationRectNote
GetAnnotationRGBNumberNote
GetAnnotationStringNote
GetAnnotationStringNote
SetAnnotationComplexNumberNote
SetAnnotationKeywordNote
SetAnnotationNoteState
SetAnnotationNumberNote
SetAnnotationRectNote
SetAnnotationRGBNumberNote
SetAnnotationStringNote

Summary
Deletes annotation note
Gets the value of an annotation
complex number note
Gets annotation note state
Gets the value of an annotation
number note
Gets the value of an annotation rect
note
Gets the value of an annotation RGB
number note
Gets the value of an annoation string
note
Gets the value of an annoation string
note
Sets the value of an annotation
complex number note
Adds a keyword to an annotation
Sets annotation note state
Sets the value of an annotation
number note
Sets the value of an annotation rect
note
Sets the value of an annotation RGB
number note
Sets the value of an annotation string
note

Strings
Operators
Name
!=
+
+
+
+
+
+

Summary
Inequality operator for strings
Concatenate a string and a real
number
Concatenate an RGB number and a
string
Concatenate a string and a complex
number
Concatenate a complex number and a
string
Concatenate a string and an RGB
number
Concatenate a real number and a
string
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

+
==

318

Concatenate a string and a string


Equality operator for strings

Functions
Name
asc
chr
left
len
mid
right
val

Summary
Returns numeric value in ascii
Returns ascii equivalent of a number
as a string
Returns the leftmost portion of a string
Returns the length of a string
Returns the middle portion of a string
Returns the rightmost portion of a
string
Converts a string to a real number

Number Conversion
Name
BaseN
BaseN
Binary
Binary
Decimal
Decimal
Hex
Hex
Octal
Octal

Summary
Convert a number to an arbitrary base
string
Convert a number to an arbitrary base
string with a fixed length
Convert a number to a binary string
with a fixed length
Convert a number to a binary string
Convert a number to a decimal string
Convert a number to a decimal string
with a fixed length
Convert a number to a hex string with
a fixed length
Convert a number to a hex string
Convert a number to an octal string
with a fixed length
Convert a number to an octal string

Input/Output
Name
CommandDown
format
GetKey
OptionDown
Result

Copyright 2012 Gatan Inc. All Rights Reserved.

Summary
Returns command key state
Formats a number printf style
Returns key
Returns option key state
Outputs formatted number to result
window

319

DigitalMicrograph

Result
Result
Result
Result
ShiftDown
SpaceDown

Outputs a complex number to the


results window
Outputs a real number to the results
window
Outputs a string to the results window
Outputs an RGB number to the results
window
Returns shift key state
Returns space key state

Dialogs
Name
Summary
Boolean ContinueCancelDialog( String Show a dialog with a continue and a
prompt )
cancel button
RealNumber getnumber( String
Show a dialog that allows the user to
prompt, RealNumber init_val,
enter a number.
RealNumber ret_val )
RealNumber getstring( String prompt, Show a dialog that allows the user to
String init_val, String ret_val )
get a string.
Boolean GetTwoImages( String title, Show a dialog that allows the user to
BasicImage image1, BasicImage
select two open images.
image2 )
Boolean GetTwoImagesWithPrompt Show a dialog that allows the user to
( String prompt, String title,
select two open images, and displays
BasicImage image1, BasicImage
a prompt.
image2 )
Boolean OkCancelDialog( String
Show a dialog with an ok and a cancel
prompt )
button.
Boolean OkDialog( String prompt )
Show a dialog with an ok button.
Boolean OpenDialog( String pathname Show a dialog that allows the user to
)
select a file for opening.
Boolean SaveAsDialog( String prompt, Show a dialog that allows the user to
String defaultName, String
select a file for saving to.
saveName )
Boolean TwoButtonDialog( String
Show a dialog with a prompt and two
prompt, String acceptLabel, String
buttons. This dialog does not show an
rejectLabel )
icon.

Miscellaneous
Name
AddCustomFunctionFileToMenu
AddScriptFileToMenu
AddScriptToMenu
Beep
CloseProgressWindow
DateStamp

Summary
Adds a custom function to the menu
Adds a script file to the menu
Adds a script string to the menu
Sounds beep
Closes the progress window
Returns date and time
Copyright 2012 Gatan Inc. All Rights Reserved.

Digital Micrograph

Delay
ExecuteScriptFile
ExecuteScriptString
GetDate
GetExceptionString
GetScreenSize
GetTime
GetUnitString
OpenAndSetProgressWindow
OpenResultsWindow
SetUnitString
Throw
Throw

Copyright 2012 Gatan Inc. All Rights Reserved.

320

Delays
Executes a script file
Executes a script string
Gets date
Get exception string
Get the screen size
Gets time
Gets the units description of an image
Opens and sets the progress window
Opens the results window
Sets the units description of an image
Throws a string exception
Throws a number exception

321

DigitalMicrograph

File Tools
109
Finding Particles
100
Fourier Masking
93
Fourier Processing
89
Functions
142

Index
-AAbout Contrast Limits
34
About Contrast Transformations
About Image Displays
32
About Lookup Tables
42
Acquisition Status
116
Analyzing Particles
102
Annotations
64
Auto-Correlations
91

39

Histogram
Histograms

-CCalculating Image Statistics


97
Changing Data Types
77
Closing Image Documents
16
Component Object
253
Control
115
Creating Image Documents
6
Cross-Correlations
92

Image Documents
56
Image Object
240
Image Operations
284
Image Preparation
98
Image Processing and Analysis
Image Status
114
Image Transformations
80
ImageDisplay Object
261
ImageDocument Object
231
Images
103
Importing Images
27
Introduction
3

Databar
29
Dialogs
207
DigitalMicrograph Environment
Display Control
113

-EEditing Annotations
61
Event Handling
168
Example Scripts
302
Expressions
129

68

-LLine Plot Tools


111
LinePlotImageDisplay Object

-D-

273

-M4

Manipulating Annotations
Masking Tools
112
Menus
192

57

-OObjects
146
Overview
1
Overview of Image Processing

77

-P-

-FFile Input and Output

113
97

-I-

-BBasic Concepts

-H-

291

Packages

291
Copyright 2012 Gatan Inc. All Rights Reserved.

Index

Particle Analysis
98
Printing Image Documents
Progress
116

Using Line Plot Legends


52
Using Line Profiles
73
Using Raster Image Displays
43
Using Regions of Interest
68
Using RGB Image Displays
45
Using Simple Math
88
Using Speadsheet Image Display
55
Using Surface Plot Image Display
44
Using Text Windows
16
Utility Functions
299

15

-RR
109
RasterImageDisplay Object
Read Tag Types
302
ROI Object
277
ROI Tools
112

269

-W-

-S-

Window Object

Saving Image Documents


9
Script Functions By Category
305
Session Information
22
Setting Image Information
107
Setting Object Information
63
Setting Preferences
19
Shortcuts
117
Slice
116
Slice Tool
76
Standard Tools
110
Statements
136
String Object
200
SurfacePlotImageDisplay Object
271

-TTagGroup Object
171
Target
115
The DigitalMicrograph Process
Threading
157
Thresholding
99
Types and Variables
127

-UUsing Calibrations
74
Using Convolutions
86
Using Filtering
82
Using Floating Palettes
17
Using Fourier Transforms
90
Using Image Displays with Complex Data
Using Image Windows
8
Using Line Plot Image Displays
45
Copyright 2012 Gatan Inc. All Rights Reserved.

55

203

322

You might also like