API Documentation

AstroImages

AstroImages.AstroImageType
AstroImage

Provides access to a FITS image along with its accompanying header and WCS information, if applicable.

source
AstroImages.CenteredType
Centered()

Pass centered as a dimesion range to automatically center a dimension along that axis.

Example:

cube = load("abc.fits", (X=Centered(), Y=Centered(), Pol=[:I, :Q, :U]))

In that case, cube will have dimsions with the centre of the image at 0 in both the X and Y axes.

source
AstroImages.imviewFunction
imview(img; clims=Percent(99.5), stretch=identity, cmap=:magma, contrast=1.0, bias=0.5, nan_color=:transparent)

Create a read only view of an array or AstroImageMat mapping its data values to Colors according to clims, stretch, and cmap.

The data is first clamped to clims, which can either be a tuple of (min, max) values or a function accepting an iterator of pixel values that returns (min, max). By default, clims=Percent(99.5) which sets the display min and max to the central 99.5 percentile range of pixel values. Convenient functions to use for clims are: extrema, Zscale, and Percent(p)

Next, the data is rescaled to [0,1] and remapped according to the function stretch. Stretch can be any monotonic fuction mapping values in the range [0,1] to some range [a,b]. Note that log(0) is not defined so is not directly supported. For a list of convenient stretch functions, see: logstretch, powstretch, squarestretch, asinhstretch, sinhstretch, powerdiststretch

Finally the data is mapped to RGB values according to cmap. If cmap is nothing, grayscale is used. ColorSchemes.jl defines hundreds of colormaps. A few nice ones for images include: :viridis, :magma, :plasma, :thermal, and :turbo.

Crucially, this function returns a view over the underlying data. If img is updated then those changes will be reflected by this view with the exception of clims which is not recalculated.

Note: if clims or stretch is a function, the pixel values passed in are first filtered to remove non-finite or missing values.

Defaults

The default values of clims, stretch, and cmap are extrema, identity, and nothing respectively. You may alter these defaults using AstroImages.set_clims!, AstroImages.set_stretch!, and AstroImages.set_cmap!.

Automatic Display

Arrays wrapped by AstroImageMat() get displayed as images automatically by calling imview on them with the default settings when using displays that support showing PNG images.

Missing data

Pixels that are NaN or missing are displayed as nan_color, which defaults to fully transparent. Pass any Colorant or color name (e.g., nan_color = :black) to render them opaque instead. Useful when the transparent default would otherwise show whatever backdrop the image is composited against. +/- Inf will be displayed as black or white respectively.

Exporting Images

The view returned by imview can be saved using general FileIO.save methods.

Example:

v = imview(data, cmap=:magma, stretch=asinhstretch, clims=Percent(95))

save("output.png", v)
source
imview(img::AbstractArray{<:Complex}; ...)

When applied to an image with complex values, display the magnitude of the pixels using imview and display the phase angle as a panel below using a cyclical color map. For more customatization, you can create a view like this yourself:

vcat(
    imview(abs.(img)),
    imview(angle.(img)),
)
source
AstroImages.implotFunction
implot(img::AstroImage; kwargs...)
implot!([ax], img::AstroImage; kwargs...)

Display an AstroImage with Makie, with support for astronomical image rendering and world coordinate system (WCS) axes. implot plots into a single axis, which makes it the right tool for composing multi-panel figures and overplotting other data; for a complete standalone panel including a colorbar, see implotview.

Note

Requires a Makie backend (e.g. using CairoMakie or using GLMakie) to be loaded.

Image Rendering

Unlike imview, which returns an array of RGBA pixels, implot maps data values to colors through Makie's colormapping pipeline so that colorbars (Makie.Colorbar(fig[1, 2], plt)) show data values with correctly placed ticks under non-linear stretches.

  • clims (default Percent(99.5)) color limits: either a tuple (lo, hi) or a callable like Percent or Zscale applied to the finite data values
  • stretch (default identity) a monotonic stretch function applied to the clims-normalized data, e.g. asinhstretch or logstretch
  • cmap (default :magma) any Makie colormap
  • contrast (default 1.0) and bias (default 0.5) scale and shift the colormap, following the SAO DS9 convention
  • nan_color (default :transparent) color for NaN and missing pixels

WCS & Image Coordinates

If provided with an AstroImage that has WCS headers set, the tick marks, axis labels, and plot grid are calculated using FITSWCS.jl. The underlying pixel coordinates are those returned by dims(img) multiplied by platescale, allowing you to overplot lines, regions, etc. using pixel coordinates (see world_to_pixel).

  • wcsn (default ' ') select which WCS transform in the headers to use for ticks & grid, by version character (' ' primary, 'A''Z' alternates)
  • wcsticks (default true if WCS headers present) display ticks, labels, and title using world coordinates
  • wcstitle (default true) when slicing a cube, display the location along unseen axes in world coordinates in the axis title
  • wcsgrid (default true when wcsticks are shown) overplot the (possibly curved) WCS coordinate grid
  • platescale (default 1) scales the underlying pixel coordinates to ease overplotting

Panel Sizing

  • width, height (default: fill the layout cell) fix the created axis's size in layout units. When only one is given, the other is derived from the image extent so the panel matches the data aspect. Fixed panel sizes keep the figure layout fully determined, so resize_to_layout!(fig) shrink-wraps the figure around its panels — sizing the panels instead of the figure is the convenient direction when composing multi-panel figures.

Defaults

The default values of clims, stretch, and cmap may be altered using AstroImages.set_clims!, AstroImages.set_stretch!, and AstroImages.set_cmap!.

source
AstroImages.implotviewFunction
fig, iv = implotview(img::AstroImage; kwargs...)
iv = implotview(fig_or_gridposition, img::AstroImage; kwargs...)

Display an AstroImage as a complete figure panel: an axis with WCS ticks, labels, and title, plus a colorbar labeled with the image's UNIT/BUNIT header when present. Accepts the rendering and WCS keyword arguments of implot, plus:

  • colorbar (default true) display the colorbar
  • colorbar_label (default from the UNIT/BUNIT header) colorbar label
  • axis (default (;)) attributes forwarded to the created Axis, overriding the WCS defaults, e.g. axis = (; title = "M42")

Passing an axis width and/or height (e.g. axis = (; height = 300)) fixes the panel's image-box size, deriving a missing dimension from the image extent. A sized view reports its footprint to the layout, so resize_to_layout!(fig) shrink-wraps a figure composed of sized views, and a standalone sized view shrink-wraps its own figure automatically. An unsized view instead fills whatever space it is given, keeping the image aspect-locked with the colorbar flush against it. This is the right behavior for interactive windows.

Called with just an image, returns (fig, iv) like other Makie blocks. Called with a figure or grid position (e.g., implotview(fig[1, 2], img)), places the panel there and returns it. The created Axis is available as iv.ax for overplotting (e.g., lines!(iv.ax, ...)), and the image plot as iv.plt.

Note

Requires a Makie backend (e.g., using CairoMakie or using GLMakie) to be loaded.

source
AstroImages.CommentType

Index for accessing a comment associated with a header keyword or COMMENT entry.

Examples

julia> img = AstroImage(randn(10, 10));

julia> img["ABC"] = 1
1

julia> img["ABC", Comment] = "A comment describing this key"
"A comment describing this key"

julia> push!(img, Comment, "The purpose of this file is to demonstrate comments")

julia> img[Comment]
1-element Vector{String}:
 "The purpose of this file is to demonstrate comments"

julia> header(img)
2-element Vector{FITSFiles.Card}:
 ABC     =                    1 / A comment describing this key
 COMMENT The purpose of this file is to demonstrate comments

A COMMENT card holds at most 72 characters and cannot contain a newline. Multi-line text is therefore split into one card per line, and lines too long to fit on a single card are wrapped:

julia> img = AstroImage(randn(10, 10));

julia> push!(img, Comment, """
       Multi-line comment
       spanning two lines.
       """)

julia> img[Comment]
2-element Vector{String}:
 "Multi-line comment"
 "spanning two lines."
source
AstroImages.HistoryType

Allows accessing and setting HISTORY header entries.

Examples

julia> img = AstroImage(randn(10, 10));

julia> push!(img, History, "2023-04-19: Added history entry.")

julia> img[History]
1-element Vector{String}:
 "2023-04-19: Added history entry."

julia> header(img)
1-element Vector{FITSFiles.Card}:
 HISTORY 2023-04-19: Added history entry.
source
AstroImages.headerFunction
header(img::AstroImage)

Return the underlying FITS header (a Vector{FITSFiles.Card}) wrapped by an AstroImage. Note that this object has less flexible getindex and setindex methods. Indexing by symbol, Comment, History, etc are not supported.

source
header(array::AbstractArray)

Returns an empty FITS header (a Vector{FITSFiles.Card}) when called with a non-AstroImage abstract array.

source
AstroImages.wcsFunction
wcs(img)

Computes and returns a Dict{Char,WCSTransform} of World Coordinate System transforms from FITSWCS.jl, keyed by WCS version character (' ' for the primary system, 'A''Z' for alternates). The results are cached after the first call, so subsequent calls are fast. Modifying a WCS header invalidates this cache automatically, so users should call wcs(...) each time rather than keeping the WCSTransform object around.

source
wcs(img, alt)

Computes and returns a single World Coordinate System WCSTransform object from FITSWCS.jl by WCS version character. This is to support files with multiple WCS transforms specified. wcs(img, ' ') selects the primary transform; wcs(img, 'A') selects the first alternate. The results are cached after the first call, so subsequent calls are fast. Modifying a WCS header invalidates this cache automatically, so users should call wcs(...) each time rather than keeping the WCSTransform object around.

source
wcs(array)

Returns a Dict{Char,WCSTransform} with a single primary WCSTransform (keyed by ' ') when called with a non-AstroImage abstract array.

source
AstroImages.WCSGridType
WCSGrid(img::AstroImageMat, ax=(1,2), coords=(first(axes(img,ax[1])),first(axes(img,ax[2]))))

Given an AstroImageMat, return information necessary to plot WCS gridlines in physical coordinates against the image's pixel coordinates. This function has to work on both plotted axes at once to handle rotation and general curvature of the WCS grid projected on the image coordinates.

source
AstroImages.composecolorsFunction
composecolors(
    images,
    cmap=["#F00", "#0F0", "#00F"];
    clims,
    stretch,
    contrast,
    bias,
    multiplier
)

Create a color composite of multiple images by applying imview and blending the results. This function can be used to create RGB composites using any number of channels (e.g. red, green, blue, and hydrogen alpha) as well as more exotic images like blending radio and optical data using two different colormaps.

cmap should be a list of colorants, named colors (see Colors.jl), or colorschemes (see ColorSchemes.jl). clims, stretch, contrast, and bias are passed on to imview. They can be a single value or a list of different values for each image.

The headers of the returned image are copied from the first image.

Examples:

# Basic RGB
composecolors([redimage, greenimage, blueimage])
# Non-linear stretch before blending
composecolors([redimage, greenimage, blueimage], stretch=asinhstretch)
# More than three channels are allowed (H alpha in pink)
composecolors(
    [antred, antgreen, antblue, anthalp],
    ["red", "green", "blue", "maroon1"],
    multiplier=[1,2,1,1]
)
# Can mix
composecolors([radioimage, xrayimage], [:ice, :magma], clims=extrema)
composecolors([radioimage, xrayimage], [:magma, :viridis], clims=[Percent(99), Zscale()])
source
AstroImages.ZscaleType
Zscale(options)(data)

Wraps PlotUtils.zscale in a callable with default parameters. This is a common algorithm for agressively stretching astronomical data to see faint structure that originated in IRAF: https://iraf.net/forum/viewtopic.php?showtopic=134139 but is now seen in many other applications/libraries (DS9, Astropy, etc.)

Usage:

imview(img, clims=Zscale())
implot(img, clims=Zscale(contrast=0.1))

Default parameters:

nsamples::Int=1000
contrast::Float64=0.25
max_reject::Float64=0.5
min_npixels::Float64=5
k_rej::Float64=2.5
max_iterations::Int=5
source
AstroImages.PercentType
Percent(99.5)

Returns a callable that calculates display limits that include the given percent of the image data. Reproduces the behaviour of the SAO DS9 scale menu.

Example:

julia> imview(img, clims=Percent(90))

This will set the limits to be the 5th percentile to the 95th percentile.

source
AstroImages.copyheaderFunction
copyheader(img::AstroImage, data) -> imgnew

Create a new image copying the header of img but using the data of the AbstractArray data. Note that changing the header of imgnew does not affect the header of img. See also: shareheader.

source
AstroImages.shareheaderFunction
shareheader(img::AstroImage, data) -> imgnew

Create a new image reusing the header dictionary of img but using the data of the AbstractArray data. The two images have synchronized header; modifying one also affects the other. See also: copyheader.

source
AstroImages.recenterFunction
recenter(img::AstroImage)
recenter(img::AstroImage, newcentx, newcenty, ...)

Adjust the dimensions of an AstroImage so that they are centered on the pixel locations given by newcentx, .. etc. This does not affect the underlying array, it just updates the dimensions associated with it by the AstroImage. If no newcent arguments are provided, center the image in all dimensions to the middle pixel (or fractional pixel).

Example:

a = AstroImage(randn(11,11))
a[1,1] # Bottom left
a[At(1),At(1)] # Bottom left
r = recenter(a, 6, 6)
r[1,1] # Still bottom left
r[At(1),At(1)] # Center pixel
source
FITSWCS.pixel_to_worldFunction
pixel_to_world(img::AstroImage, pixcoords; wcsn = ' ', all = false, parent = false)

Given an AstroImage, look up the world coordinates of the pixels given by pixcoords using FITSWCS.jl and a WCSTransform calculated from any FITS header present in img. If no WCS information is in the header, or the axes are all linear, this will just return pixel coordinates.

pixcoords may be a vector (one coordinate) or a matrix whose columns are coordinates, given in the order of dims(img), i.e., 1-based positions within your current selection of the image. For example, if you select a slice like this:

julia> cube = load("some-3d-cube.fits")
julia> slice = cube[10:20, 30:40, 5]

Then to look up the coordinates of the pixel in the bottom left corner of slice, run:

julia> world_coords = pixel_to_world(slice, [1, 1])
[10, 30]

If WCS information was present in the header of cube, then those coordinates would be resolved using axis 1, 2, and 3 respectively.

Keyword arguments:

  • wcsn: Which WCS version character to use (' ' for the primary system, 'A''Z' for alternates).
  • all=true: Return world coordinates for all WCS axes (in WCS axis order), including axes frozen by slicing, instead of only the selected dims.
  • parent=true: Interpret pixcoords as 1-based pixel positions in the parent (original) array, rather than in the current slice.

Note: Coordinates must be provided in the order of dims(img). If you transpose an image, the order you pass the coordinates should not change.

source
FITSWCS.world_to_pixelFunction
world_to_pixel(img::AstroImage, worldcoords; wcsn = ' ', parent = false)

Given an AstroImage, look up the pixel coordinates corresponding to the world coordinates worldcoords. This is the inverse of pixel_to_world. World coordinates are resolved using FITSWCS.jl and a WCSTransform calculated from any FITS header present in img. If no WCS information is in the header, or the axes are all linear, this just returns the input coordinates.

worldcoords may be a vector (one coordinate) or a matrix whose columns are coordinates, given in the order of dims(img). The returned pixel coordinates need not lie within the bounds of the image, and in general lie at fractional pixel positions.

By default the result contains one 1-based slice-local pixel coordinate per selected dim, in dims(img) order. With parent = true the world coordinates are inverted through the full parent-frame transform instead. Axes frozen by slicing contribute their exact world values, and the result contains parent pixel coordinates for all WCS axes, in WCS axis order.

If the current slice drops a pixel axis that the remaining world axes depend on (e.g. one axis of a celestial longitude/latitude pair), the remaining world coordinates alone do not determine pixel coordinates and an ArgumentError is thrown. Invert through the full transform via world_to_pixel(wcs(img, wcsn), fullworldcoords) instead.

source
AstroImages.world_transformFunction
world_transform(img::AstroImage; wcsn = ' ', platescale = 1)
world_transform(plt_or_view)

Return a Makie.Transformation that maps world coordinates of the image's two plotted dimensions (in the WCS's native world units, typically degrees for celestial axes) to the pixel coordinate space that implot draws in. Pass it to a Makie plotting function via the transformation keyword to plot world-coordinate data directly over an image.

fig, iv = implotview(img)
scatter!(iv.ax, ra_deg, dec_deg; transformation = world_transform(iv))

Called with the plot returned by implot or the view returned by implotview, as above, the image, wcsn, and platescale are taken from it directly. When called with an image, pass the same wcsn and platescale values as the image plot.

The transformed positions feed Makie's autolimits, so overplotted world-coordinate data co-registers with the image without manual world_to_pixel calls. The transformation is invertible (Makie.inverse_transform), so interactive tools that need the reverse mapping keep working.

Note

Wrap-around of angular coordinates (e.g., right ascension crossing 0°/360°) is not special-cased.

Note

Requires a Makie backend (e.g., using CairoMakie or using GLMakie) to be loaded.

source

DimensionalData

DimensionalData.Dimensions.X
DimensionalData.Dimensions.Y
DimensionalData.Dimensions.Z
DimensionalData.Dimensions.Dim
DimensionalData.Dimensions.Lookups.At
DimensionalData.Dimensions.Lookups.Near
DimensionalData.Dimensions.dims
DimensionalData.Dimensions.refdims

FileIO

FileIO.load
FileIO.save
FileIO.query