karabo.imaging.image
Overview
This package provides the Image base class. It is used in the Karabo package to store and manipulate image data.
Classes
- class Image(*, path: Path | str, data: Literal[None] = None, header: Literal[None] = None, **kwargs: Any)
- class Image(*, path: Literal[None] = None, data: ndarray[Any, dtype[float64]], header: Header, **kwargs: Any)
- __init__(*, path: Path | str, data: Literal[None] = None, header: Literal[None] = None, **kwargs: Any) None
- __init__(*, path: Literal[None] = None, data: ndarray[Any, dtype[float64]], header: Header, **kwargs: Any) None
- circle() None
For each frequency channel and polarisation, cutout the pixel values, only keeping data for a circle of the computed radius, centered at the center of the image. This is an in-place transformation of the data.
- Returns:
None (data of current Image instance is transformed in-place)
- cutout(center_xy: Tuple[float, float], size_xy: Tuple[float, float]) Image
Cutout the image to the given size and center.
- Parameters:
center_xy – Center of the cutout in pixel coordinates
size_xy – Size of the cutout in pixel coordinates
- Returns:
Cutout of the image
- Return type:
- get_beam_parameters() BeamType
Gets the beam-parameters fom the image-header.
“bmaj”: FWHM of the major axis of the elliptical Gaussian beam in arcsec “bmin”: FWHM of the minor minor axis of the elliptical Gaussian beam in arcsec “bpa”: position angle of the major axis of the elliptical Gaussian beam in
degrees, counter-clock from the North direction
- Returns:
“bmaj” (arcsec), “bmin” (arcsec), “bpa” (deg)
- classmethod get_corners_in_world(header: Header) ndarray[Any, dtype[float64]]
Get the image corners RA,DEC of bl, br, tr & tl from header in deg.
Assumes that header has at least two axis RA & DEC.
- Parameters:
header – Header to extract image-infos.
- Returns:
Corners in world coordinates [deg] with shape 4x2.
- get_dimensions_of_image() List[int]
Get the dimensions of this Image as an array.
- Returns:
List with the dimensions.
- Return type:
List[int]
- get_power_spectrum(resolution: float = 0.0005, signal_channel: int | None = None) Tuple[ndarray[Any, dtype[float64]], ndarray[Any, dtype[float64]]]
Calculate the power spectrum of this image.
- Parameters:
resolution – Resolution in radians needed for conversion from Jy to Kelvin
signal_channel – channel containing both signal and noise (arr of same shape as nchan of Image), optional
- Returns:
profile: Brightness temperature for each angular scale in Kelvin
theta_axis: Angular scale data in degrees
- Return type:
(profile, theta_axis)
- get_quality_metric() Dict[str, Any]
Get image statistics. Statistics include :
Shape of Image –> ‘shape’
Max Value –> ‘max’
Min Value –> ‘min’
Max Value absolute –> ‘max-abs’
Root mean square (RMS) –> ‘rms’
Sum of values –> ‘sum’
Median absolute –> ‘median-abs’
Median absolute deviation median –> ‘median-abs-dev-median’
Median –> ‘median’
Mean –> ‘mean’
- Returns:
Dictionary holding all image statistics
- has_beam_parameters() bool
Check if the image has the beam parameters in the header.
- Parameters:
image – Image to check
- Returns:
True if the image has the beam parameters in the header
- overplot_with_skymodel(sky: SkyModel, filename: Path | str | None = None, block: bool = False, channel_index: int = 0, stokes_index: int = 0, vmin_image: float | None = None, vmax_image: float | None = None) None
Create a plot with the current image data, as well as an overlay of sources from a given SkyModel instance.
- Parameters:
sky – a SkyModel instance, with sources to be plotted.
filename – path to the file where the final plot will be saved. If None, the plot is not saved.
block – whether plotting should block the remaining of the script.
channel_index – Which frequency channel to show in the plot. Defaults to 0.
stokes_index – Which polarisation to show in the plot. Defaults to 0 (stokesI).
vmin_image – Limits for colorbar of Image plot.
vmax_image – Limits for colorbar of Image plot.
- plot(title: str | None = None, xlim: Tuple[float, float] | None = None, ylim: Tuple[float, float] | None = None, figsize: Tuple[float, float] | None = None, colorbar_label: str | None = None, xlabel: str | None = None, ylabel: str | None = None, cmap: str | None = 'jet', origin: Literal['upper', 'lower'] | None = 'lower', wcs_enabled: bool = True, invert_xaxis: bool = False, filename: str | None = None, block: bool = False, **kwargs: Any) None
Plots the image
- Parameters:
title – the title of the colormap
xlim – RA-limit of plot
ylim – DEC-limit of plot
figsize – figsize as tuple
title – plot title
xlabel – xlabel
ylabel – ylabel
cmap – matplotlib color map
origin – place the [0, 0] index of the array in the upper left or lower left corner of the Axes
wcs_enabled – Use wcs transformation? Default is True
invert_xaxis – Do you want to invert the xaxis? Default is False
filename – Set to path/fname to save figure (set extension to fname to overwrite .png default)
block – Whether plotting should block the remaining of the script
**kwargs – matplotlib kwargs for scatter & Collections, e.g. customize s, vmin or vmax
- plot_power_spectrum(resolution: float = 0.0005, signal_channel: int | None = None, path: Path | str | None = None, block: bool = False) None
Plot the power spectrum of this image.
- Parameters:
resolution – Resolution in radians needed for conversion from Jy to Kelvin
signal_channel – channel containing both signal and noise (arr of same shape as nchan of Image), optional
save_png – True if result should be saved, default = False
block – Whether plotting should block the remaining of the script
- plot_side_by_side_with_skymodel(sky: SkyModel, filename: Path | str | None = None, block: bool = False, channel_index: int = 0, stokes_index: int = 0, vmin_sky: float = 0, vmax_sky: float = inf, vmin_image: float = 0, vmax_image: float = inf) None
Create a plot with two panels:
the current image data, and
a scatter plot of sources from a given SkyModel instance.
- Parameters:
sky – a SkyModel instance, with sources to be plotted.
filename – path to the file where the final plot will be saved. If None, the plot is not saved.
block – whether plotting should block the remaining of the script.
channel_index – Which frequency channel to show in the plot. Defaults to 0.
stokes_index – Which polarisation to show in the plot. Defaults to 0 (stokesI).
vmin_sky – Limits for colorbar of SkyModel scatter plot.
vmax_sky – Limits for colorbar of SkyModel scatter plot.
vmin_image – Limits for colorbar of Image plot.
vmax_image – Limits for colorbar of Image plot.
- resample(shape: Tuple[int, ...], **kwargs: Any) None
Resamples the image to the given shape using SciPy’s RegularGridInterpolator for bilinear interpolation. See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.RegularGridInterpolator.html
- Parameters:
shape – The desired shape of the image
kwargs – Keyword arguments for the interpolation function
- split_image(N: int, overlap: int = 0) List[Image]
Split the image into N x N equal-sized sections with optional overlap.
- Parameters:
N (int) – The number of sections to split the image into along one axis. The total number of image sections will be N^2. It is assumed that the image can be divided into N equal parts along both axes. If this is not the case (e.g., image size is not a multiple of N), the sections on the edges will have fewer pixels.
overlap (int, optional) – The number of pixels by which adjacent image sections will overlap. Default is 0, meaning no overlap. Negative overlap means that there will be empty sections between the cutouts.
- Returns:
A list of cutout sections of the image. Each element in the list is a 2D array representing a section of the image.
- Return type:
List[Image]
Notes
The function calculates the step size for both the x and y dimensions by dividing the dimension size by N. It then iterates over N steps in both dimensions to generate starting and ending indices for each cutout section, taking the overlap into account.
The cutout function (not shown) is assumed to take the center (x, y) coordinates and the (width, height) of the desired cutout section and return the corresponding 2D array from the image.
The edge sections will be equal to or smaller than the sections in the center of the image if the image size is not an exact multiple of N.
Examples
>>> # Assuming `self.data` is a 4D array with shape (C, Z, X, Y) >>> # and `self.cutout` method is defined >>> image = Image() >>> cutouts = image.split_image(4, overlap=10) >>> len(cutouts) 16 # because 4x4 grid
- write_to_file(path: Path | str, overwrite: bool = False) None
Write an Image to path as .fits
- Parameters:
path – Full path of the file
overwrite – Overwrite the file if it already exists? Defaults to False
- class ImageMosaicker(reproject_function: ~typing.Callable[[...], ~typing.Any] = <function reproject_interp>, combine_function: str = 'mean', match_background: bool = False, background_reference: int | None = None)
A class to handle the combination of multiple images into a single mosaicked image. See: https://reproject.readthedocs.io/en/stable/mosaicking.html
More information on the parameters can be found in the documentation: https://reproject.readthedocs.io/en/stable/api/reproject.mosaicking.reproject_and_coadd.html However, here the most common to tune are explained.
- Parameters:
reproject_function (callable, optional) – The function to use for the reprojection.
combine_function ({'mean', 'sum'}) – The type of function to use for combining the values into the final image.
match_background (bool, optional) – Whether to match the backgrounds of the images.
background_reference (None or int, optional) – If None, the background matching will make it so that the average of the corrections for all images is zero. If an integer, this specifies the index of the image to use as a reference.
- __init__(reproject_function: ~typing.Callable[[...], ~typing.Any] = <function reproject_interp>, combine_function: str = 'mean', match_background: bool = False, background_reference: int | None = None)
- get_optimal_wcs(images: List[Image], projection: str = 'SIN', **kwargs: Any) Tuple[WCS, tuple[int, int]]
Set the optimal WCS for the given images. See: https://reproject.readthedocs.io/en/stable/api/reproject.mosaicking.find_optimal_celestial_wcs.html # noqa: E501
- Parameters:
images (list) – A list of images to combine.
projection (str, optional) – Three-letter code for the WCS projection, such as ‘SIN’ or ‘TAN’.
**kwargs (dict, optional) – Additional keyword arguments to be passed to the reprojection function.
- Returns:
The optimal WCS for the given images and the size of this WCS
- Return type:
Tuple[WCS, tuple[int, int]]
- mosaic(images: List[Image], wcs: Tuple[WCS, Tuple[int, int]] | None = None, input_weights: List[str | fits.HDUList | fits.PrimaryHDU | NDArray[np.float64]] | None = None, hdu_in: int | str | None = None, hdu_weights: int | str | None = None, shape_out: Tuple[int] | None = None, image_for_header: Image | None = None, **kwargs: Any) Tuple[Image, NDArray[np.float64]]
Combine the provided images into a single mosaicked image.
- Parameters:
images (list) – A list of images to combine.
wcs (tuple, optional) – The WCS to use for the mosaicking. Will be calculated with get_optimal_wcs if not passed.
input_weights (list, optional) – If specified, an iterable with the same length as images, containing weights for each image.
shape_out (tuple, optional) – The shape of the output data. If None, it will be computed from the images.
hdu_in (int or str, optional) – If one or more items in input_data is a FITS file or an HDUList instance, specifies the HDU to use.
hdu_weights (int or str, optional) – If one or more items in input_weights is a FITS file or an HDUList instance, specifies the HDU to use.
image_for_header (Image, optional) – From which image the header should be used to readd the lost information by the mosaicking because some information is not propagated.
**kwargs (dict, optional) – Additional keyword arguments to be passed to the reprojection function.
- Returns:
The final mosaicked image as a FITS HDU and the footprint of the final mosaicked image.
- Return type:
Tuple[Image, NDArray[np.float64]]
- Raises:
ValueError – If less than two images are provided.