or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

coordinate-systems.mdfitting-operations.mdfunctionals.mdimage-processing.mdindex.mdquantities-units.mdtable-operations.md

image-processing.mddocs/

0

# Image Processing

1

2

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.

3

4

## Core Imports

5

6

```python

7

from casacore.images import image

8

from casacore.images.coordinates import coordinatesystem, directioncoordinate, spectralcoordinate

9

```

10

11

## Capabilities

12

13

### Image Access and Creation

14

15

Open existing images or create new ones with support for multiple astronomical image formats.

16

17

```python { .api }

18

def image(imagename, **kwargs):

19

"""

20

Open or create an astronomical image.

21

22

Parameters:

23

- imagename: str, path to image file

24

- mode: str, access mode ('r', 'w', 'rw')

25

- overwrite: bool, overwrite existing image

26

- shape: list, shape for new image

27

- coordsys: coordinatesystem, coordinate system for new image

28

29

Returns:

30

image object

31

"""

32

```

33

34

### Image Data Access

35

36

Retrieve and modify image data with support for slicing, masking, and partial reads for large images.

37

38

```python { .api }

39

class image:

40

def getdata(self, blc=[], trc=[], inc=[]):

41

"""

42

Get image data array.

43

44

Parameters:

45

- blc: list, bottom-left corner indices (default [])

46

- trc: list, top-right corner indices (default [])

47

- inc: list, increment per axis (default [])

48

49

Returns:

50

numpy array with image data

51

"""

52

53

def putdata(self, value, blc=[], trc=[], inc=[]):

54

"""

55

Set image data array.

56

57

Parameters:

58

- value: numpy array, data to write

59

- blc: list, bottom-left corner indices (default [])

60

- trc: list, top-right corner indices (default [])

61

- inc: list, increment per axis (default [])

62

"""

63

64

def getslice(self, axes=[], coord=[], **kwargs):

65

"""

66

Get image slice along specified axes.

67

68

Parameters:

69

- axes: list, axes for slicing

70

- coord: list, coordinate values for fixed axes

71

72

Returns:

73

numpy array with slice data

74

"""

75

76

def getmask(self, name=""):

77

"""

78

Get image mask.

79

80

Parameters:

81

- name: str, mask name (empty for default mask)

82

83

Returns:

84

numpy boolean array with mask

85

"""

86

87

def putmask(self, mask, name=""):

88

"""

89

Set image mask.

90

91

Parameters:

92

- mask: numpy boolean array, mask to set

93

- name: str, mask name (empty for default mask)

94

"""

95

96

def haslock(self):

97

"""Check if image is locked."""

98

99

def lock(self, mode="write"):

100

"""Lock image for exclusive access."""

101

102

def unlock(self):

103

"""Release image lock."""

104

```

105

106

### Image Properties and Metadata

107

108

Access image properties, coordinate systems, and metadata information.

109

110

```python { .api }

111

class image:

112

def name(self):

113

"""Get image name/path."""

114

115

def shape(self):

116

"""Get image shape as list."""

117

118

def ndim(self):

119

"""Get number of image dimensions."""

120

121

def size(self):

122

"""Get total number of pixels."""

123

124

def datatype(self):

125

"""Get image data type."""

126

127

def imagetype(self):

128

"""Get image format type."""

129

130

def coordinates(self):

131

"""

132

Get coordinate system.

133

134

Returns:

135

coordinatesystem object

136

"""

137

138

def setcoordinates(self, coordsys):

139

"""

140

Set coordinate system.

141

142

Parameters:

143

- coordsys: coordinatesystem object

144

"""

145

146

def summary(self, header=True):

147

"""

148

Get image summary information.

149

150

Parameters:

151

- header: bool, include header information

152

153

Returns:

154

dict with summary information

155

"""

156

157

def history(self):

158

"""Get image processing history."""

159

160

def sethistory(self, history):

161

"""

162

Set image processing history.

163

164

Parameters:

165

- history: list of str, history entries

166

"""

167

```

168

169

### Image Analysis and Statistics

170

171

Calculate image statistics, moments, and perform analysis operations.

172

173

```python { .api }

174

class image:

175

def statistics(self, robust=True, list=True, **kwargs):

176

"""

177

Calculate image statistics.

178

179

Parameters:

180

- robust: bool, use robust statistics (default True)

181

- list: bool, list results (default True)

182

- axes: list, axes for statistics calculation

183

- region: dict, region specification

184

- mask: str, mask expression

185

186

Returns:

187

dict with statistics (min, max, mean, rms, etc.)

188

"""

189

190

def moments(self, moments=[0], axis=-1, **kwargs):

191

"""

192

Calculate image moments.

193

194

Parameters:

195

- moments: list, moment numbers to calculate

196

- axis: int, axis along which to calculate moments

197

- region: dict, region specification

198

- mask: str, mask expression

199

200

Returns:

201

list of image objects with moment images

202

"""

203

204

def maxfit(self, region={}):

205

"""

206

Fit maximum pixel in region.

207

208

Parameters:

209

- region: dict, region specification

210

211

Returns:

212

dict with fit results

213

"""

214

215

def findsources(self, **kwargs):

216

"""

217

Find sources in image.

218

219

Returns:

220

dict with source information

221

"""

222

```

223

224

### Image Operations

225

226

Perform image processing operations including arithmetic, convolution, and transformations.

227

228

```python { .api }

229

class image:

230

def subimage(self, blc=[], trc=[], inc=[], dropdegenerate=False, **kwargs):

231

"""

232

Create subimage.

233

234

Parameters:

235

- blc: list, bottom-left corner

236

- trc: list, top-right corner

237

- inc: list, increment per axis

238

- dropdegenerate: bool, drop degenerate axes

239

- region: dict, region specification

240

- mask: str, mask expression

241

242

Returns:

243

image object with subimage

244

"""

245

246

def rebin(self, factors, **kwargs):

247

"""

248

Rebin image by integer factors.

249

250

Parameters:

251

- factors: list, rebinning factors per axis

252

253

Returns:

254

image object with rebinned image

255

"""

256

257

def regrid(self, outfile, shape=[], csys=None, **kwargs):

258

"""

259

Regrid image to new coordinate system.

260

261

Parameters:

262

- outfile: str, output image name

263

- shape: list, output shape

264

- csys: coordinatesystem, target coordinate system

265

- method: str, interpolation method

266

267

Returns:

268

image object with regridded image

269

"""

270

271

def convolve(self, kernel, **kwargs):

272

"""

273

Convolve image with kernel.

274

275

Parameters:

276

- kernel: numpy array or image, convolution kernel

277

- scale: float, kernel scaling

278

279

Returns:

280

image object with convolved image

281

"""

282

283

def smooth(self, type="gauss", **kwargs):

284

"""

285

Smooth image with specified kernel.

286

287

Parameters:

288

- type: str, smoothing type ('gauss', 'boxcar')

289

- major: str, major axis size

290

- minor: str, minor axis size

291

- pa: str, position angle

292

293

Returns:

294

image object with smoothed image

295

"""

296

```

297

298

### Image Format Operations

299

300

Import/export images to different formats and handle format-specific operations.

301

302

```python { .api }

303

class image:

304

def tofits(self, fitsfile, velocity=False, optical=False, **kwargs):

305

"""

306

Export image to FITS format.

307

308

Parameters:

309

- fitsfile: str, output FITS filename

310

- velocity: bool, convert frequency to velocity

311

- optical: bool, use optical velocity convention

312

- bitpix: int, FITS bits per pixel

313

- minpix: float, minimum pixel value

314

- maxpix: float, maximum pixel value

315

- overwrite: bool, overwrite existing file

316

"""

317

318

def tofloat(self):

319

"""Convert image to float data type."""

320

321

def tocomplex(self):

322

"""Convert image to complex data type."""

323

324

def convertflux(self, major, minor, type="gauss", **kwargs):

325

"""

326

Convert between peak and integrated flux.

327

328

Parameters:

329

- major: str, major axis size

330

- minor: str, minor axis size

331

- type: str, beam type

332

333

Returns:

334

float, conversion factor

335

"""

336

```

337

338

### Coordinate System Classes

339

340

Handle astronomical coordinate systems including celestial, spectral, and linear coordinates.

341

342

```python { .api }

343

class coordinatesystem:

344

def __init__(self):

345

"""Create empty coordinate system."""

346

347

def copy(self):

348

"""Create copy of coordinate system."""

349

350

def ncoordinates(self):

351

"""Get number of coordinate systems."""

352

353

def naxes(self):

354

"""Get number of axes."""

355

356

def names(self):

357

"""Get coordinate names."""

358

359

def axisnames(self, type="world"):

360

"""

361

Get axis names.

362

363

Parameters:

364

- type: str, name type ('world' or 'pixel')

365

366

Returns:

367

list of axis names

368

"""

369

370

def units(self):

371

"""Get coordinate units."""

372

373

def increment(self):

374

"""Get coordinate increments."""

375

376

def referencevalue(self):

377

"""Get reference values."""

378

379

def referencepixel(self):

380

"""Get reference pixels."""

381

382

def projection(self):

383

"""Get coordinate projections."""

384

385

def epoch(self):

386

"""Get coordinate epoch."""

387

388

def observer(self):

389

"""Get observer information."""

390

391

def telescope(self):

392

"""Get telescope information."""

393

394

def settelescope(self, telescope):

395

"""Set telescope information."""

396

397

def toworld(self, pixel, format="n"):

398

"""

399

Convert pixel to world coordinates.

400

401

Parameters:

402

- pixel: list, pixel coordinates

403

- format: str, output format

404

405

Returns:

406

dict with world coordinates

407

"""

408

409

def topixel(self, world):

410

"""

411

Convert world to pixel coordinates.

412

413

Parameters:

414

- world: list, world coordinates

415

416

Returns:

417

dict with pixel coordinates

418

"""

419

```

420

421

```python { .api }

422

class directioncoordinate:

423

def __init__(self, refcode="J2000", **kwargs):

424

"""

425

Create direction coordinate.

426

427

Parameters:

428

- refcode: str, reference frame ('J2000', 'B1950', etc.)

429

- proj: str, projection type

430

- projpar: list, projection parameters

431

- refval: list, reference values

432

- refpix: list, reference pixels

433

- incr: list, increments

434

"""

435

436

def referencecode(self):

437

"""Get reference frame code."""

438

439

def projection(self):

440

"""Get projection information."""

441

442

def setreferencecode(self, refcode):

443

"""Set reference frame code."""

444

445

class spectralcoordinate:

446

def __init__(self, refcode="LSRK", **kwargs):

447

"""

448

Create spectral coordinate.

449

450

Parameters:

451

- refcode: str, reference frame

452

- restfreq: float, rest frequency

453

- refval: float, reference value

454

- refpix: float, reference pixel

455

- incr: float, increment

456

"""

457

458

def restfrequency(self):

459

"""Get rest frequency."""

460

461

def setrestfrequency(self, freq):

462

"""Set rest frequency."""

463

464

class linearcoordinate:

465

def __init__(self, names=[], units=[], **kwargs):

466

"""

467

Create linear coordinate.

468

469

Parameters:

470

- names: list, axis names

471

- units: list, axis units

472

- refval: list, reference values

473

- refpix: list, reference pixels

474

- incr: list, increments

475

"""

476

477

class stokescoordinate:

478

def __init__(self, stokes=["I"]):

479

"""

480

Create Stokes coordinate.

481

482

Parameters:

483

- stokes: list, Stokes parameters

484

"""

485

486

def stokes(self):

487

"""Get Stokes parameters."""

488

489

class tabularcoordinate:

490

def __init__(self, pixel=[], world=[], **kwargs):

491

"""

492

Create tabular coordinate.

493

494

Parameters:

495

- pixel: list, pixel values

496

- world: list, world values

497

- names: list, axis names

498

- units: list, axis units

499

"""

500

```

501

502

## Usage Examples

503

504

### Basic Image Operations

505

506

```python

507

from casacore.images import image

508

509

# Open an image

510

img = image('galaxy.fits')

511

512

# Get basic information

513

print(f"Image shape: {img.shape()}")

514

print(f"Data type: {img.datatype()}")

515

print(f"Coordinate system: {img.coordinates()}")

516

517

# Get image data

518

data = img.getdata()

519

print(f"Data shape: {data.shape}, min: {data.min()}, max: {data.max()}")

520

521

# Get statistics

522

stats = img.statistics()

523

print(f"Mean: {stats['mean']}, RMS: {stats['rms']}")

524

525

# Create subimage

526

subimg = img.subimage(blc=[100, 100], trc=[200, 200])

527

subdata = subimg.getdata()

528

529

img.close()

530

subimg.close()

531

```

532

533

### Image Analysis

534

535

```python

536

# Calculate moments (integrated intensity, velocity field)

537

moments = img.moments(moments=[0, 1, 2], axis=2) # Along frequency axis

538

539

# Moment 0: integrated intensity

540

int_intensity = moments[0]

541

int_data = int_intensity.getdata()

542

543

# Find sources

544

sources = img.findsources(nmax=10, cutoff=0.01)

545

print(f"Found {len(sources)} sources")

546

547

# Image statistics in region

548

region_stats = img.statistics(region={'blc': [50, 50], 'trc': [150, 150]})

549

print(f"Region mean: {region_stats['mean']}")

550

```

551

552

### Coordinate System Manipulation

553

554

```python

555

from casacore.images.coordinates import coordinatesystem, directioncoordinate, spectralcoordinate

556

557

# Get and modify coordinate system

558

csys = img.coordinates()

559

print(f"Number of axes: {csys.naxes()}")

560

print(f"Axis names: {csys.axisnames()}")

561

print(f"Units: {csys.units()}")

562

563

# Convert between pixel and world coordinates

564

pixel_coord = [100, 100, 10] # x, y, frequency channel

565

world_coord = csys.toworld(pixel_coord)

566

print(f"World coordinates: {world_coord}")

567

568

# Convert back to pixels

569

pixel_back = csys.topixel(world_coord['numeric'])

570

print(f"Pixel coordinates: {pixel_back}")

571

```

572

573

### Image Format Conversion

574

575

```python

576

# Export to FITS

577

img.tofits('output.fits', overwrite=True, velocity=True)

578

579

# Create regridded image

580

regridded = img.regrid('regridded.image',

581

shape=[512, 512, 64],

582

method='linear')

583

584

# Smooth image

585

smoothed = img.smooth(type='gauss', major='5arcsec', minor='3arcsec', pa='30deg')

586

587

regridded.close()

588

smoothed.close()

589

```