Python bindings for the CASACORE radio astronomy library providing comprehensive interfaces for table operations, image processing, coordinate systems, and astronomical measurements.
—
Multi-dimensional astronomical image processing with support for FITS, HDF5, MIRIAD, and casacore paged image formats. Includes coordinate system handling, image statistics, regridding, subimage operations, and comprehensive support for astronomical coordinate systems.
from casacore.images import image
from casacore.images.coordinates import coordinatesystem, directioncoordinate, spectralcoordinateOpen existing images or create new ones with support for multiple astronomical image formats.
def image(imagename, **kwargs):
"""
Open or create an astronomical image.
Parameters:
- imagename: str, path to image file
- mode: str, access mode ('r', 'w', 'rw')
- overwrite: bool, overwrite existing image
- shape: list, shape for new image
- coordsys: coordinatesystem, coordinate system for new image
Returns:
image object
"""Retrieve and modify image data with support for slicing, masking, and partial reads for large images.
class image:
def getdata(self, blc=[], trc=[], inc=[]):
"""
Get image data array.
Parameters:
- blc: list, bottom-left corner indices (default [])
- trc: list, top-right corner indices (default [])
- inc: list, increment per axis (default [])
Returns:
numpy array with image data
"""
def putdata(self, value, blc=[], trc=[], inc=[]):
"""
Set image data array.
Parameters:
- value: numpy array, data to write
- blc: list, bottom-left corner indices (default [])
- trc: list, top-right corner indices (default [])
- inc: list, increment per axis (default [])
"""
def getslice(self, axes=[], coord=[], **kwargs):
"""
Get image slice along specified axes.
Parameters:
- axes: list, axes for slicing
- coord: list, coordinate values for fixed axes
Returns:
numpy array with slice data
"""
def getmask(self, name=""):
"""
Get image mask.
Parameters:
- name: str, mask name (empty for default mask)
Returns:
numpy boolean array with mask
"""
def putmask(self, mask, name=""):
"""
Set image mask.
Parameters:
- mask: numpy boolean array, mask to set
- name: str, mask name (empty for default mask)
"""
def haslock(self):
"""Check if image is locked."""
def lock(self, mode="write"):
"""Lock image for exclusive access."""
def unlock(self):
"""Release image lock."""Access image properties, coordinate systems, and metadata information.
class image:
def name(self):
"""Get image name/path."""
def shape(self):
"""Get image shape as list."""
def ndim(self):
"""Get number of image dimensions."""
def size(self):
"""Get total number of pixels."""
def datatype(self):
"""Get image data type."""
def imagetype(self):
"""Get image format type."""
def coordinates(self):
"""
Get coordinate system.
Returns:
coordinatesystem object
"""
def setcoordinates(self, coordsys):
"""
Set coordinate system.
Parameters:
- coordsys: coordinatesystem object
"""
def summary(self, header=True):
"""
Get image summary information.
Parameters:
- header: bool, include header information
Returns:
dict with summary information
"""
def history(self):
"""Get image processing history."""
def sethistory(self, history):
"""
Set image processing history.
Parameters:
- history: list of str, history entries
"""Calculate image statistics, moments, and perform analysis operations.
class image:
def statistics(self, robust=True, list=True, **kwargs):
"""
Calculate image statistics.
Parameters:
- robust: bool, use robust statistics (default True)
- list: bool, list results (default True)
- axes: list, axes for statistics calculation
- region: dict, region specification
- mask: str, mask expression
Returns:
dict with statistics (min, max, mean, rms, etc.)
"""
def moments(self, moments=[0], axis=-1, **kwargs):
"""
Calculate image moments.
Parameters:
- moments: list, moment numbers to calculate
- axis: int, axis along which to calculate moments
- region: dict, region specification
- mask: str, mask expression
Returns:
list of image objects with moment images
"""
def maxfit(self, region={}):
"""
Fit maximum pixel in region.
Parameters:
- region: dict, region specification
Returns:
dict with fit results
"""
def findsources(self, **kwargs):
"""
Find sources in image.
Returns:
dict with source information
"""Perform image processing operations including arithmetic, convolution, and transformations.
class image:
def subimage(self, blc=[], trc=[], inc=[], dropdegenerate=False, **kwargs):
"""
Create subimage.
Parameters:
- blc: list, bottom-left corner
- trc: list, top-right corner
- inc: list, increment per axis
- dropdegenerate: bool, drop degenerate axes
- region: dict, region specification
- mask: str, mask expression
Returns:
image object with subimage
"""
def rebin(self, factors, **kwargs):
"""
Rebin image by integer factors.
Parameters:
- factors: list, rebinning factors per axis
Returns:
image object with rebinned image
"""
def regrid(self, outfile, shape=[], csys=None, **kwargs):
"""
Regrid image to new coordinate system.
Parameters:
- outfile: str, output image name
- shape: list, output shape
- csys: coordinatesystem, target coordinate system
- method: str, interpolation method
Returns:
image object with regridded image
"""
def convolve(self, kernel, **kwargs):
"""
Convolve image with kernel.
Parameters:
- kernel: numpy array or image, convolution kernel
- scale: float, kernel scaling
Returns:
image object with convolved image
"""
def smooth(self, type="gauss", **kwargs):
"""
Smooth image with specified kernel.
Parameters:
- type: str, smoothing type ('gauss', 'boxcar')
- major: str, major axis size
- minor: str, minor axis size
- pa: str, position angle
Returns:
image object with smoothed image
"""Import/export images to different formats and handle format-specific operations.
class image:
def tofits(self, fitsfile, velocity=False, optical=False, **kwargs):
"""
Export image to FITS format.
Parameters:
- fitsfile: str, output FITS filename
- velocity: bool, convert frequency to velocity
- optical: bool, use optical velocity convention
- bitpix: int, FITS bits per pixel
- minpix: float, minimum pixel value
- maxpix: float, maximum pixel value
- overwrite: bool, overwrite existing file
"""
def tofloat(self):
"""Convert image to float data type."""
def tocomplex(self):
"""Convert image to complex data type."""
def convertflux(self, major, minor, type="gauss", **kwargs):
"""
Convert between peak and integrated flux.
Parameters:
- major: str, major axis size
- minor: str, minor axis size
- type: str, beam type
Returns:
float, conversion factor
"""Handle astronomical coordinate systems including celestial, spectral, and linear coordinates.
class coordinatesystem:
def __init__(self):
"""Create empty coordinate system."""
def copy(self):
"""Create copy of coordinate system."""
def ncoordinates(self):
"""Get number of coordinate systems."""
def naxes(self):
"""Get number of axes."""
def names(self):
"""Get coordinate names."""
def axisnames(self, type="world"):
"""
Get axis names.
Parameters:
- type: str, name type ('world' or 'pixel')
Returns:
list of axis names
"""
def units(self):
"""Get coordinate units."""
def increment(self):
"""Get coordinate increments."""
def referencevalue(self):
"""Get reference values."""
def referencepixel(self):
"""Get reference pixels."""
def projection(self):
"""Get coordinate projections."""
def epoch(self):
"""Get coordinate epoch."""
def observer(self):
"""Get observer information."""
def telescope(self):
"""Get telescope information."""
def settelescope(self, telescope):
"""Set telescope information."""
def toworld(self, pixel, format="n"):
"""
Convert pixel to world coordinates.
Parameters:
- pixel: list, pixel coordinates
- format: str, output format
Returns:
dict with world coordinates
"""
def topixel(self, world):
"""
Convert world to pixel coordinates.
Parameters:
- world: list, world coordinates
Returns:
dict with pixel coordinates
"""class directioncoordinate:
def __init__(self, refcode="J2000", **kwargs):
"""
Create direction coordinate.
Parameters:
- refcode: str, reference frame ('J2000', 'B1950', etc.)
- proj: str, projection type
- projpar: list, projection parameters
- refval: list, reference values
- refpix: list, reference pixels
- incr: list, increments
"""
def referencecode(self):
"""Get reference frame code."""
def projection(self):
"""Get projection information."""
def setreferencecode(self, refcode):
"""Set reference frame code."""
class spectralcoordinate:
def __init__(self, refcode="LSRK", **kwargs):
"""
Create spectral coordinate.
Parameters:
- refcode: str, reference frame
- restfreq: float, rest frequency
- refval: float, reference value
- refpix: float, reference pixel
- incr: float, increment
"""
def restfrequency(self):
"""Get rest frequency."""
def setrestfrequency(self, freq):
"""Set rest frequency."""
class linearcoordinate:
def __init__(self, names=[], units=[], **kwargs):
"""
Create linear coordinate.
Parameters:
- names: list, axis names
- units: list, axis units
- refval: list, reference values
- refpix: list, reference pixels
- incr: list, increments
"""
class stokescoordinate:
def __init__(self, stokes=["I"]):
"""
Create Stokes coordinate.
Parameters:
- stokes: list, Stokes parameters
"""
def stokes(self):
"""Get Stokes parameters."""
class tabularcoordinate:
def __init__(self, pixel=[], world=[], **kwargs):
"""
Create tabular coordinate.
Parameters:
- pixel: list, pixel values
- world: list, world values
- names: list, axis names
- units: list, axis units
"""from casacore.images import image
# Open an image
img = image('galaxy.fits')
# Get basic information
print(f"Image shape: {img.shape()}")
print(f"Data type: {img.datatype()}")
print(f"Coordinate system: {img.coordinates()}")
# Get image data
data = img.getdata()
print(f"Data shape: {data.shape}, min: {data.min()}, max: {data.max()}")
# Get statistics
stats = img.statistics()
print(f"Mean: {stats['mean']}, RMS: {stats['rms']}")
# Create subimage
subimg = img.subimage(blc=[100, 100], trc=[200, 200])
subdata = subimg.getdata()
img.close()
subimg.close()# Calculate moments (integrated intensity, velocity field)
moments = img.moments(moments=[0, 1, 2], axis=2) # Along frequency axis
# Moment 0: integrated intensity
int_intensity = moments[0]
int_data = int_intensity.getdata()
# Find sources
sources = img.findsources(nmax=10, cutoff=0.01)
print(f"Found {len(sources)} sources")
# Image statistics in region
region_stats = img.statistics(region={'blc': [50, 50], 'trc': [150, 150]})
print(f"Region mean: {region_stats['mean']}")from casacore.images.coordinates import coordinatesystem, directioncoordinate, spectralcoordinate
# Get and modify coordinate system
csys = img.coordinates()
print(f"Number of axes: {csys.naxes()}")
print(f"Axis names: {csys.axisnames()}")
print(f"Units: {csys.units()}")
# Convert between pixel and world coordinates
pixel_coord = [100, 100, 10] # x, y, frequency channel
world_coord = csys.toworld(pixel_coord)
print(f"World coordinates: {world_coord}")
# Convert back to pixels
pixel_back = csys.topixel(world_coord['numeric'])
print(f"Pixel coordinates: {pixel_back}")# Export to FITS
img.tofits('output.fits', overwrite=True, velocity=True)
# Create regridded image
regridded = img.regrid('regridded.image',
shape=[512, 512, 64],
method='linear')
# Smooth image
smoothed = img.smooth(type='gauss', major='5arcsec', minor='3arcsec', pa='30deg')
regridded.close()
smoothed.close()Install with Tessl CLI
npx tessl i tessl/pypi-python-casacore