NRAO Home > CASA > CASA Toolkit Reference Manual

1.1.1 image - Tool

Operations on images
Requires: coordsys Synopsis



An Image tool provides access to CASA images. Currently only single precision floating point CASA images are supported by all methods in the Image tooland complex-valued images are supported by many, but not all, methods.

Image tools also provide direct (native) access to FITS and Miriad images. You can also convert these foreign formats to CASA format (for optimum processing speed).

It is important to note that many methods return new image tools that are attached to an image that method has created. Even if one does not intend on using this returned tool, it is important to capture it and run done() on it or it will continue to use resources unnecessarily, eg

new_image_tool = ia.collapse("")  
# do things with new_image_tool and then run done() on it  

Overview of Image tool functionality


We refer to a CASA image file when we are referring to the actual data stored on disk. The name that you give a CASA image file is actually the name of a directory containing a collection of CASA tables which together constitute the image file. But you only need to refer to the directory name and you can think of it as one logical file.

Whenever we use the word “image”, we are just using it in a generic sense. CASA images are manipulated with an Image tool associated with, or bound to, the actual image file. Note that some image tools don’t have a disk file associated with them. These are called “virtual” images and are discussed ??

When an image is stored on disk, it can, in principle, be stored in a variety of ways. For example, the image could be stored row by row; this is the way that most older generation packages store images. It makes for very fast row by row access, but very slow in other directions (e.g. extract all the profiles along the third axis of an image). A CASA image file is stored with what is called tiling. This means that small multi-dimensional chunks (a tile) are stored sequentially. It means that row by row access is a little slower, but access speed is essentially the same in all directions. This in turn means that you don’t need to (and can’t !) reorder images.

Here are some simple examples using image tools.

print "\t----\t Intro Ex 1 \t----"  
ia.maketestimage(’zz’,overwrite=true)# Make test image; writes disk file called ’zz’  
print ia.summary()                   # Summarize (to logger)  
print ia.statistics()                # Evaluate statistics over entire image  
box =[10,10], [50,50])       # Make a pixel box region with regionmanager  
im2 = ia.subimage(’zz2’, box, overwrite=true)  # Make a subimage  called ’zz2’  
print im2.statistics()                    # Evaluate statistics  
print "CLEANING UP OLD zz2.amp/zz2.phase IF THEY EXIST.  IGNORE WARNINGS!"  
im2.fft(amp=’zz2.amp’,phase=’zz2.phase’)  # FFT subimage and store amp and phase  
im2.done()      # Release tool resources - disk file unaffected  
ia.close()      # DO NOT DONE DEFAULT IMAGE TOOL ia!!!  

Foreign Images

The Image tool also provides you with native access to some foreign image formats. Presently, these are FITS (Floar, Double, Short and Long are supported) and Miriad. This means that you don’t have to convert the file to native CASA format in order to access the image. For example:

print "\t----\t Intro Ex 2 \t----"  
pathname=os.environ.get("CASAPATH") # Assumes environment variable is set  
datapath2=pathname+"/data/demo/Images/test_image"              # Access FITS image’im.mir’)              # Access Miriad image (no image in repository)              # Access casa image  
#ims = ia.newimagefromimage(infile=datapath1, region=rg.quarter())  
# rg.quarter() not implemented yet so has grabbed entire image  
ims = ia.newimagefromimage(infile=datapath1)[0.25,0.25],[0.75,0.75],frac=true)  
subim = ims.subimage(region=innerquarter)  
ims.done()                      # done on-the-fly image tool  
subim.done()                    # done on-the-fly image tool  
ia.close()                      # close (not done) default image analysis tool  
Each of these Image tools has access to all the same \toolfunctions.

Where ever you see an argument in an Image tool function which is an input image disk file, that disk file can be a CASA, FITS, or Miriad image file.

There are some performance penalties that you should be aware of. Firstly, because CASA images are tiled (see above) you get the same access speed regardless of how you access the image. FITS and Miriad images are not tiled. This means that the performance for these Image tools will be poorer for certain operations. For example, extracting a profile along the third axis of an image, or re-ordering an image with the display library.

Secondly, for FITS images, masked values are indicated via “magic value”. This means that the mask is worked out on the fly every time you access the image.

If you find performance is not good enough or you want a writable image, then use appropriate function (fromfits to convert to a native CASA image.

Virtual Images

We also have Image tools that are not associated one-to-one with disk files; these are called “virtual” images (see also the article in the AugustNewsLetter). For example, with the image calculator, imagecalc, one can create an expression which may contain many images. You can write the result of the expression out to a disk image file, but if you wish, you can also just maintain the expression, evaluating it each time it is needed - nothing is ever written out to disk in this case. There are other Image functions like this (the documentation for each one explains what it does). The rules are:

Coordinate Systems

An image contains a Coordinate System. A Coordsys tool is used to manipulate the Coordinate System. An Image tool allows you to recover the Coordinate System into a Coordsys tool through the coordsys function. You can set a new Coordinate System with the setcoordsys function.

You can do some direct coordinate conversion via the Image tool functions toworld, topixel, and coordmeasures. The actual work is done by a Coordsys tool, for which these Image tool functions are just wrappers.

Lattice Expression Language (LEL)

LEL allows you to manipulate expressions involving images. For example, add this image to that image, or multiply the miniumum value of that image by the square root of this image. The LEL syntax is quite rich and is described in detail in note 223.

LEL is accessed via the imagecalc and the calc tool functions. Here are some examples.

print "\t----\t Intro Ex 3 \t----"  
ia.maketestimage(’zz’, overwrite=true) # Make nonvirtual test image  
ia.calc(’zz + min(zz)’)                # Make the minimum value zero  

In this example the Image tool is associated with the non-virtual disk file zz. This image file name is used in an LEL expression.

Note that for image file names with special characters in them (like a  
dash for example), you should (double) escape those characters or put  
the file name in double quotes. E.g.  
print "\t----\t Intro Ex 4 \t----"  
ia.maketestimage("test-im", overwrite=true)  
im1 = ia.imagecalc(pixels=’test\\-im’)  # Note double escape required  
im2 = ia.imagecalc(pixels=’"test-im"’)  


A region-of-interest or simply, region, designates which pixels of the image you are interested in for some (generally) astrophysical reason. This complements the pixel mask (see below) which specifies which pixels are good or bad (for statistical reasons). Regions-of-interest are generated and manipulated with the Regionmanager tool.

Briefly, a region-of-interest may be either a simple shape such as a multi-dimensional box, or a 2-D polygon, or some compound combination of regions-of-interest. For example, a 2-D polygon defined in the X and Y axes extended along the Z axis, or perhaps a union or intersection of regions.

See the Regionmanager documentation for more details on regions.

Regions are always supplied to tool functions via the region argument.

Pixel mask

A pixel mask specifies which pixels are to be considered good (value T) or bad (value F). For example, you may have imported a FITS file which has blanked pixels in it. These will be converted into pixel mask elements whose values are bad (F). Or you may have made an error analysis of an image and computed via a statistical test that certain pixels should be masked out for future analysis.

If there is no pixel mask, all pixels are considered good (if you retrieve the pixel mask when there is none, you will get an all good mask). Pixels for which the pixel mask value is bad are not used in computations (e.g. in the calculation of statistics, moments or convolution).

The image may contain zero, one, or more pixel masks. However, only one mask will be designated as the default mask. This is the pixel mask that is actually applied to the data. You can also indicate that none of the pixel masks are the default, so that effectively an all good pixel mask is applied. The function summary includes in its summary of the image the names of the masks (the first listed, if not in square brackets, is the default).

Pixel masks are handled with the function maskhandler. This allows you to find the names of pixel masks, delete them, copy them, nominate the default and so on. It is not used to change the value of pixel masks.

The functions with which you can change pixel mask values are putregion (put Boolean array), calcmask (put result of Boolean LEL expression), and set (put scalar Boolean).

The argument ’mask’

There is an argument, mask, which can be supplied to many functions. It is supplied with either a mask region-of-interest (generated via the function wmask) or a LEL Boolean expression string (the same string you would have supplied to the above Regionmanager function). Generally, one just supplies the expression string.

The LEL expression is simply used to generate a pixel mask which is then applied in addition to any default pixel mask in the image (a logical OR). For example

print "\t----\t Intro Ex 5 \t----"  
ia.maketestimage(’zz’, overwrite=true)  
ia.statistics(mask=’zz > 0’)      # Only evaluate for positive values  
ia.calcmask (mask=’(2*zz) > 0’)   # Create a new mask which is T (good)  
                                  # when twice the image values are  
                                  # positive, else F  

The mask expression must in general conform (shape and coordinates) with the image (i.e. that associated with the Image tool).

When mask is used with function calcmask, a persistent pixel mask is created and stored with the image. With all other functions, the mask argument operates as a transient (or On-The-Fly [OTF]) pixel mask. It can be very handy for analysing or displaying images with different masking criteria.

Often I will refer to the “total input mask”. This is the combination (logical OR) of the default pixel mask (if any) and the OTF mask (if any).

In the following example we open a Rotation Measure image. We then evaluate statistics and display it where only those pixels whose error in the Rotation Measure (image file rmerr) is less than the specified value are shown; the others are masked. The nice thing is you can experiment with different pixel masks until you are satisfied, whereupon you might then make the pixel mask persistent with the calcmask function.

print "\t----\t Intro Ex 6 \t----"  
#myim = ia.newimagefromimage(’rm’)  
#myim.calcmask (mask=’rmerr<20’)     # Make persistent mask  

Finally, a subtlety that is worth explaining.

print "\t----\t Intro Ex 7 \t----"  
ia.maketestimage(’zz’, overwrite=true)  
ia.statistics(mask=’zz>0’)                 # Mask of zz ignored  
ia.statistics(mask=’mask(zz) && zz>0’)     # Mask of zz used  
In the first example, any default mask associated with the image {\sff  
zz} is ignored.  Only the pixel values are looked at.  In the second  
example, the mask of {\sff zz} is also taken into account via the LEL  
{\cf mask} function. That is, the transient output mask is T (good) only when  
the mask of {\sff zz} is T and the expression {\cf zz>0} is T.  

A useful part of LEL to use with the mask argument is the indexin function. This enables the user to specify a mask based upon selected pixel coordinates or indices (specified 0-rel) rather than image values. For example

print "\t----\t Intro Ex 8 \t----"  
print ia.getregion(mask=’indexin(0, [4:9, 14, 18:19])’,getmask=true)  
#[False False False False True True True True True True False False False  
# False True False False False True True]  

You can see the mask is good (T) for the specified indices along the specified axis. You can also pass in a premade variable for the specification if you like, viz.

print "\t----\t Intro Ex 9 \t----"  
axis = "0"  
sel = "[4:9, 14, 18:19]"  
print ia.getregion(mask=’indexin(’+axis+’,’+sel+’)’,getmask=true)  
#[False False False False True True True True True True False False False  
# False True False False False True True]  

This capability is useful for fitting functions.

Pixel masks and Regions

Some comment about the combination of pixel masks and regions-of-interest is useful here. See the Regionmanager tool for basic information about regions-of-interest first.

Regions are provided to Image tool functions via the standard region function argument.

Consider a simple polygonal region. This region-of-interest is defined by a bounding box, the polygonal vertices, and a mask called a region mask. The region mask specifies whether a pixel within the bounding box is inside or outside the polygon. For a simple box region-of-interest, there is obviously no need for a region mask.

Now imagine that you wish to recover the pixel mask of an image from a polygonal region-of-interest. The mask is returned to you in regular Boolean array. Thus, the shape of the returned mask array reflects the bounding-box of the polygonal region. If the actual pixel mask that you apply is all good, then the retrieved mask would be good inside of the polygonal region and bad outside of it. If the actual pixel mask had some bad values in it as well, the retrieved mask would be bad outside of the polygonal region. Inside the polygonal region it would be bad if the pixel mask was bad. More simply put, the mask that you recover is just a logical “and” of the pixel mask and the region mask; if the pixel mask is T and the region mask is T then the retrieved mask is T (good), else it is F (bad).

Finally, note that if you use the region and mask (the OTF mask) arguments together then they operate as follows. The shape of the Boolean expression provided by mask must be the same shape as the image to which it is being applied. The region is applied equally to the image and the mask expression. For example

print "\t----\t Intro Ex 10 \t----"  
#rm1 = ia.newimagefromimage(’rm’)  
#rm2 = ia.newimagefromimage(’rmerr’)  
#[128 128]  
#[128 128]  
#r =[10,10], [50,50])  
#rm1.statistics(region=r, mask=’rmerr<10’) # region applied to  
                                              # ’rmerr’ and ’rm’  


newimage Construct a new image analysis tool using the specified image. (Also known as newimagefromfile.)
newimagefromfileConstruct a new image analysis tool using the specified image. (Also known as newimage.)
imagecalc Perform mathematical calculations on an image or images.
collapse Collapse an image along a specified axis, computing a specified aggregate function of pixels along that axis.
decimate Remove planes from an image.
imageconcat Construct a CASA image by concatenating images
fromarray Construct a CASA image from a numerical (integer or float) array
fromascii This function converts a pre-existing ascii file into a CASA image.
fromfits Construct a CASA image by conversion from a FITS image file
fromimage Construct a (sub)image from a region of a CASA image
fromshape Construct an empty CASA image from a shape
maketestimage Construct a CASA image from a test FITS file
adddegaxes Add degenerate axes of the specified type to the image
addnoise Add noise to the image
convolve Convolve image with an array or another image
boundingbox Get the bounding box of the specified region
boxcar Convolve one axis of image with a boxcar kernel
brightnessunit Get the image brightness unit
calc Image calculator
calcmask Image mask calculator
close Close the image tool
continuumsub Image plane continuum subtraction
convertflux Convert peak intensity to/from flux density for a 2D Gaussian.
convolve2d Convolve image by a 2D kernel
coordsys Get the Coordinate System of the image
coordmeasures Convert from pixel to world coordinate wrapped as Measures
decompose Separate a complex image into individual components
deconvolvecomponentlistDeconvolve a componentlist from the restoring beam
deconvolvefrombeam Helper function to deconvolve the given source Gaussian from a beam Gaussian to return a model Gaussian
beamforconvolvedsize Determine the size of the beam necessary to convolve with the given source to reach the given convolved (source+beam) size
commonbeam Determine a beam to which all beams in an image can be convolved.
remove Delete the image file associated with this image tool
removefile Delete an unattached image file from disk. Note: use remove() if the image file is attached to the image tool.
done Destroy this image tool
fft FFT the image
findsources Find point sources in the sky
fitprofile Fit gaussians and/or polynomials to a 1-dimensional profile.
fitcomponents Fit 2-dimensional models to an image.
fromrecord Generate an image from a record
getchunk Get the pixel values from a regular region of the image into an array
getregion Get pixels or mask from a region-of-interest of the image
getprofile Get values and mask for a one dimensional profile along a specified image axis by applying an aggregate function.
getslice Get 1-D slice from the image
hanning Convolve one axis of image with a Hanning kernel
haslock Does this image have any locks set?
histograms Compute histograms from the image
history Recover and/or list the history file
insert Insert specified image into this image
isopen Is this Image tool open?
ispersistent Is the image persistent?
lock Acquire a lock on the image
makecomplexMake a complex image
maskhandler Handle pixel masks
miscinfo Get the miscellaneous information record from an image
modify Modify image with a model
maxfit Find maximum and do parabolic fit in the sky
moments Compute moments from an image
name Name of the image file this tool is attached to
open Open a new image file with this image tool
pad Pad the perimeter of the direction plane with a number of pixels of specified value and mask.
crop Crop masked pixels from the perimeter of an image.
pixelvalue Get value of image and mask at specified pixel coordinate
putchunk Put pixels from an array into a regular region of the image
putregion Put pixels and mask into a region-of-interest of the image
rebin Rebin an image by the specified integer factors
regrid regrid this image to the specified Coordinate System
transpose Transpose the image.
rotate rotate the direction coordinate axes attached to the image and regrid the image to the rotated Coordinate System
rotatebeam rotate the image’s beam(s) counterclockwise through the specified angle.
rename Rename the image file associated with this image tool
replacemaskedpixelsreplace the values of pixels which are masked bad
beamarea Get the beam area.
restoringbeam Get the restoring beam(s).
sepconvolve Separable convolution
set Set pixel and/or mask values with a scalar in a region-of-interest of the image
setbrightnessunit Set the image brightness unit
setcoordsys Set new Coordinate System
sethistory Set the history for an image
setmiscinfo Set the miscellaneous information record for an image
shape Length of each axis in the image
setrestoringbeam Set the restoringbeam
statistics Compute statistics from the image
twopointcorrelation Compute two point correlation function from the image
subimage Create a (sub)image from a region of the image
summary Summarize basic information about the image
tofits Convert the image to a FITS file
toASCII Convert the image to an ASCII file
torecord Return a record containg the image associated with this tool
type Return the type of this tool
topixel Convert from world to pixel coordinate
toworld Convert from pixel to world coordinate
unlock Release any lock on the image
newimagefromarray Construct a CASA image from an array
newimagefromfits Construct a CASA image by conversion from a FITS image file
newimagefromimageConstruct an on-the-fly image tool from a region of a CASA image file
newimagefromshapeConstruct an empty CASA image from a shape
pbcor Construct a primary beam corrected image from an image and a primary beam
pv Construct a position-velocity image between two points in the direction plane.
makearray Construct an initialized multi-dimensional array.
isconform Returns true of the shape, coordinate system, and axes order of the specified image matches this image.

    image.newimage - Function
    image.newimagefromfile - Function
    image.imagecalc - Function
    image.collapse - Function
    image.decimate - Function
    image.imageconcat - Function
    image.fromarray - Function
    image.fromascii - Function
    image.fromfits - Function
    image.fromimage - Function
    image.fromshape - Function
    image.maketestimage - Function
    image.adddegaxes - Function
    image.addnoise - Function
    image.convolve - Function
    image.boundingbox - Function
    image.boxcar - Function
    image.brightnessunit - Function
    image.calc - Function
    image.calcmask - Function
    image.close - Function
    image.continuumsub - Function
    image.convertflux - Function
    image.convolve2d - Function
    image.coordsys - Function
    image.coordmeasures - Function
    image.decompose - Function
    image.deconvolvecomponentlist - Function
    image.deconvolvefrombeam - Function
    image.beamforconvolvedsize - Function
    image.commonbeam - Function
    image.remove - Function
    image.removefile - Function
    image.done - Function
    image.fft - Function
    image.findsources - Function
    image.fitprofile - Function
    image.fitcomponents - Function
    image.fromrecord - Function
    image.getchunk - Function
    image.getregion - Function
    image.getprofile - Function
    image.getslice - Function
    image.hanning - Function
    image.haslock - Function
    image.histograms - Function
    image.history - Function
    image.insert - Function
    image.isopen - Function
    image.ispersistent - Function
    image.lock - Function
    image.makecomplex - Function
    image.maskhandler - Function
    image.miscinfo - Function
    image.modify - Function
    image.maxfit - Function
    image.moments - Function - Function - Function
    image.pad - Function
    image.crop - Function
    image.pixelvalue - Function
    image.putchunk - Function
    image.putregion - Function
    image.rebin - Function
    image.regrid - Function
    image.transpose - Function
    image.rotate - Function
    image.rotatebeam - Function
    image.rename - Function
    image.replacemaskedpixels - Function
    image.beamarea - Function
    image.restoringbeam - Function
    image.sepconvolve - Function
    image.set - Function
    image.setbrightnessunit - Function
    image.setcoordsys - Function
    image.sethistory - Function
    image.setmiscinfo - Function
    image.shape - Function
    image.setrestoringbeam - Function
    image.statistics - Function
    image.twopointcorrelation - Function
    image.subimage - Function
    image.summary - Function
    image.tofits - Function
    image.toASCII - Function
    image.torecord - Function
    image.type - Function
    image.topixel - Function
    image.toworld - Function
    image.unlock - Function
    image.newimagefromarray - Function
    image.newimagefromfits - Function
    image.newimagefromimage - Function
    image.newimagefromshape - Function
    image.pbcor - Function
    image.pv - Function
    image.makearray - Function
    image.isconform - Function

More information about CASA may be found at the CASA web page

Copyright 2016 Associated Universities Inc., Washington, D.C.

This code is available under the terms of the GNU General Public Lincense

Home | Contact Us | Directories | Site Map | Help | Privacy Policy | Search