or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

algorithms.mdcommand-line.mdeds-tomography.mdevaluation.mdfile-io.mdindex.mdvisualization.md

algorithms.mddocs/

0

# Image Processing Algorithms

1

2

Comprehensive image processing capabilities for electron microscopy data including correlation-based alignment, peak detection, Fourier operations, distortion correction, and mathematical fitting functions.

3

4

## Capabilities

5

6

### Image Correlation and Alignment

7

8

Functions for aligning images and image stacks using cross-correlation and phase-correlation techniques.

9

10

```python { .api }

11

def image_cross_corr(image, reference, real_filter=1, k_filter=1):

12

"""

13

Calculate cross-correlation between two images.

14

15

Parameters:

16

- image: numpy.ndarray, source image to align

17

- reference: numpy.ndarray, reference image to align to

18

- real_filter: numpy.ndarray, real space filter (default=1)

19

- k_filter: numpy.ndarray, Fourier space filter (default=1)

20

21

Returns:

22

numpy.ndarray: Cross-correlation result

23

"""

24

25

def image_correlate(image1, image2, **kwargs):

26

"""

27

Align images using cross-correlation.

28

29

Parameters:

30

- image1: numpy.ndarray, reference image

31

- image2: numpy.ndarray, image to align

32

33

Returns:

34

numpy.ndarray: Aligned image

35

"""

36

37

def image_phase_correlate(image, reference, real_filter=1, k_filter=1, shift_func='shift', verbose=False):

38

"""

39

Align images using phase-correlation.

40

41

Parameters:

42

- image: numpy.ndarray, image to align

43

- reference: numpy.ndarray, reference image to align to

44

- real_filter: numpy.ndarray, real space filter (default=1)

45

- k_filter: numpy.ndarray, Fourier space filter (default=1)

46

- shift_func: str, shift method ('shift' or 'roll')

47

- verbose: bool, plot cross-correlation for debugging

48

49

Returns:

50

tuple: (aligned_image, shifts) - aligned image and applied shifts

51

"""

52

53

def stack_align(image_stack, **kwargs):

54

"""

55

Align stack of images using cross-correlation.

56

57

Parameters:

58

- image_stack: numpy.ndarray, 3D array of images (z, y, x)

59

60

Returns:

61

numpy.ndarray: Aligned image stack

62

"""

63

```

64

65

### Array Operations

66

67

Basic array manipulation and rebinning functions for data processing.

68

69

```python { .api }

70

def rebin(im, f, funcType='sum'):

71

"""

72

Rebin 2D arrays with sum or mean reduction.

73

74

Parameters:

75

- im: numpy.ndarray, input 2D array

76

- f: int, factor to rebin by (must be integer)

77

- funcType: str, 'sum' or 'mean' reduction

78

79

Returns:

80

numpy.ndarray: Rebinned array

81

"""

82

```

83

84

### Image Moments and Geometry

85

86

Functions for calculating image moments, centroids, and geometric properties.

87

88

```python { .api }

89

def moments(image, order=3):

90

"""

91

Calculate raw image moments.

92

93

Parameters:

94

- image: numpy.ndarray, input image

95

- order: int, maximum moment order

96

97

Returns:

98

numpy.ndarray: Raw moments array

99

"""

100

101

def moments_central(image, center=None, order=3):

102

"""

103

Calculate central image moments.

104

105

Parameters:

106

- image: numpy.ndarray, input image

107

- center: tuple, center coordinates (y, x)

108

- order: int, maximum moment order

109

110

Returns:

111

numpy.ndarray: Central moments array

112

"""

113

114

def centroid(moments_raw):

115

"""

116

Find centroid from raw moments.

117

118

Parameters:

119

- moments_raw: numpy.ndarray, raw moments from moments()

120

121

Returns:

122

tuple: Centroid coordinates (y, x)

123

"""

124

125

def moment_angle(moments_central):

126

"""

127

Calculate orientation angle from central moments.

128

129

Parameters:

130

- moments_central: numpy.ndarray, central moments

131

132

Returns:

133

float: Orientation angle in radians

134

"""

135

```

136

137

### Fourier Operations

138

139

Precise image transformations using FFT-based operations.

140

141

```python { .api }

142

def shearImage(image, shear_x=0, shear_y=0):

143

"""

144

Exact shear using FFT frequency space.

145

146

Parameters:

147

- image: numpy.ndarray, input image

148

- shear_x: float, shear factor in x direction

149

- shear_y: float, shear factor in y direction

150

151

Returns:

152

numpy.ndarray: Sheared image

153

"""

154

155

def shiftImage(image, shift_x=0, shift_y=0):

156

"""

157

Exact shift using FFT frequency space.

158

159

Parameters:

160

- image: numpy.ndarray, input image

161

- shift_x: float, shift in x direction (pixels)

162

- shift_y: float, shift in y direction (pixels)

163

164

Returns:

165

numpy.ndarray: Shifted image

166

"""

167

168

def rotateImage(image, angle):

169

"""

170

Exact rotation using three shears.

171

172

Parameters:

173

- image: numpy.ndarray, input image

174

- angle: float, rotation angle in radians

175

176

Returns:

177

numpy.ndarray: Rotated image

178

"""

179

180

def bandpass_filter(image, low_freq, high_freq):

181

"""

182

Apply bandpass filter in frequency domain.

183

184

Parameters:

185

- image: numpy.ndarray, input image

186

- low_freq: float, low frequency cutoff

187

- high_freq: float, high frequency cutoff

188

189

Returns:

190

numpy.ndarray: Filtered image

191

"""

192

```

193

194

### Peak Detection

195

196

2D and 3D peak finding algorithms with lattice analysis capabilities.

197

198

```python { .api }

199

def peakFind2D(image, sigma=1, threshold=0.1, min_distance=1):

200

"""

201

2D peak detection in images.

202

203

Parameters:

204

- image: numpy.ndarray, input 2D image

205

- sigma: float, Gaussian filter sigma

206

- threshold: float, peak threshold

207

- min_distance: int, minimum distance between peaks

208

209

Returns:

210

numpy.ndarray: Peak coordinates (N, 2) array

211

"""

212

213

def peakFind3D(volume, sigma=1, threshold=0.1, min_distance=1):

214

"""

215

3D peak detection in volumes.

216

217

Parameters:

218

- volume: numpy.ndarray, input 3D volume

219

- sigma: float, Gaussian filter sigma

220

- threshold: float, peak threshold

221

- min_distance: int, minimum distance between peaks

222

223

Returns:

224

numpy.ndarray: Peak coordinates (N, 3) array

225

"""

226

227

def enforceMinDist(peaks, min_distance):

228

"""

229

Enforce minimum distance between peaks.

230

231

Parameters:

232

- peaks: numpy.ndarray, peak coordinates

233

- min_distance: float, minimum distance

234

235

Returns:

236

numpy.ndarray: Filtered peak coordinates

237

"""

238

239

def remove_xrays(peaks, image, threshold=3.0):

240

"""

241

Remove X-ray artifacts from peak list.

242

243

Parameters:

244

- peaks: numpy.ndarray, peak coordinates

245

- image: numpy.ndarray, source image

246

- threshold: float, removal threshold

247

248

Returns:

249

numpy.ndarray: Cleaned peak coordinates

250

"""

251

```

252

253

### Lattice Analysis

254

255

Functions for generating, refining, and analyzing crystal lattices from peak data.

256

257

```python { .api }

258

def lattice2D(peaks, lattice_params):

259

"""

260

Generate 2D lattice from parameters.

261

262

Parameters:

263

- peaks: numpy.ndarray, reference peaks

264

- lattice_params: dict, lattice parameters

265

266

Returns:

267

numpy.ndarray: Generated lattice points

268

"""

269

270

def lattice3D(peaks, lattice_params):

271

"""

272

Generate 3D lattice from parameters.

273

274

Parameters:

275

- peaks: numpy.ndarray, reference peaks

276

- lattice_params: dict, lattice parameters

277

278

Returns:

279

numpy.ndarray: Generated lattice points

280

"""

281

282

def refineLattice2D(peaks, initial_params):

283

"""

284

Refine 2D lattice parameters.

285

286

Parameters:

287

- peaks: numpy.ndarray, experimental peaks

288

- initial_params: dict, initial lattice parameters

289

290

Returns:

291

dict: Refined lattice parameters

292

"""

293

294

def refineLattice3D(peaks, initial_params):

295

"""

296

Refine 3D lattice parameters.

297

298

Parameters:

299

- peaks: numpy.ndarray, experimental peaks

300

- initial_params: dict, initial lattice parameters

301

302

Returns:

303

dict: Refined lattice parameters

304

"""

305

306

def match_lattice_peaks(experimental_peaks, theoretical_lattice):

307

"""

308

Match experimental peaks to theoretical lattice.

309

310

Parameters:

311

- experimental_peaks: numpy.ndarray, detected peaks

312

- theoretical_lattice: numpy.ndarray, theoretical positions

313

314

Returns:

315

dict: Matching results and statistics

316

"""

317

318

def calculate_unit_cell(peaks, lattice_vectors):

319

"""

320

Calculate unit cell parameters from peaks.

321

322

Parameters:

323

- peaks: numpy.ndarray, lattice peaks

324

- lattice_vectors: numpy.ndarray, lattice vectors

325

326

Returns:

327

dict: Unit cell parameters

328

"""

329

```

330

331

### Gaussian and Mathematical Functions

332

333

Multi-dimensional Gaussian functions and mathematical models for fitting.

334

335

```python { .api }

336

def gauss1D(x, amplitude, center, sigma, offset=0):

337

"""

338

1D Gaussian function.

339

340

Parameters:

341

- x: numpy.ndarray, coordinate array

342

- amplitude: float, peak amplitude

343

- center: float, peak center

344

- sigma: float, standard deviation

345

- offset: float, baseline offset

346

347

Returns:

348

numpy.ndarray: Gaussian values

349

"""

350

351

def gauss2D(coords, amplitude, center_x, center_y, sigma_x, sigma_y, offset=0):

352

"""

353

2D Gaussian function.

354

355

Parameters:

356

- coords: tuple, (x, y) coordinate arrays

357

- amplitude: float, peak amplitude

358

- center_x: float, x center coordinate

359

- center_y: float, y center coordinate

360

- sigma_x: float, x standard deviation

361

- sigma_y: float, y standard deviation

362

- offset: float, baseline offset

363

364

Returns:

365

numpy.ndarray: 2D Gaussian values

366

"""

367

368

def gauss3D(coords, amplitude, center_x, center_y, center_z,

369

sigma_x, sigma_y, sigma_z, offset=0):

370

"""

371

3D Gaussian function.

372

373

Parameters:

374

- coords: tuple, (x, y, z) coordinate arrays

375

- amplitude: float, peak amplitude

376

- center_x: float, x center coordinate

377

- center_y: float, y center coordinate

378

- center_z: float, z center coordinate

379

- sigma_x: float, x standard deviation

380

- sigma_y: float, y standard deviation

381

- sigma_z: float, z standard deviation

382

- offset: float, baseline offset

383

384

Returns:

385

numpy.ndarray: 3D Gaussian values

386

"""

387

388

def voigt(x, amplitude, center, sigma, gamma):

389

"""

390

Voigt peak function for fitting.

391

392

Parameters:

393

- x: numpy.ndarray, coordinate array

394

- amplitude: float, peak amplitude

395

- center: float, peak center

396

- sigma: float, Gaussian width

397

- gamma: float, Lorentzian width

398

399

Returns:

400

numpy.ndarray: Voigt profile values

401

"""

402

403

def fit_peaks_gauss2d(image, peaks, fit_region_size=10):

404

"""

405

Fit 2D Gaussian peaks to image data.

406

407

Parameters:

408

- image: numpy.ndarray, input image

409

- peaks: numpy.ndarray, initial peak positions

410

- fit_region_size: int, region size for fitting

411

412

Returns:

413

dict: Fitted parameters for each peak

414

"""

415

```

416

417

### Distortion Correction

418

419

Functions for correcting lens distortions and geometric aberrations.

420

421

```python { .api }

422

def optimize_center(points, initial_center):

423

"""

424

Optimize center position for distortion correction.

425

426

Parameters:

427

- points: numpy.ndarray, calibration points

428

- initial_center: tuple, initial center guess

429

430

Returns:

431

tuple: Optimized center coordinates

432

"""

433

434

def optimize_distortion(points, center, initial_params):

435

"""

436

Optimize distortion parameters.

437

438

Parameters:

439

- points: numpy.ndarray, calibration points

440

- center: tuple, distortion center

441

- initial_params: dict, initial distortion parameters

442

443

Returns:

444

dict: Optimized distortion parameters

445

"""

446

447

def correct_distortion(image, distortion_params):

448

"""

449

Correct image distortion.

450

451

Parameters:

452

- image: numpy.ndarray, input image

453

- distortion_params: dict, distortion correction parameters

454

455

Returns:

456

numpy.ndarray: Corrected image

457

"""

458

```

459

460

### Radial Profile Analysis

461

462

Functions for analyzing radial intensity profiles in images.

463

464

```python { .api }

465

def calc_radialprofile(image, center, max_radius=None):

466

"""

467

Calculate radial intensity profile.

468

469

Parameters:

470

- image: numpy.ndarray, input image

471

- center: tuple, center coordinates (y, x)

472

- max_radius: float, maximum radius for profile

473

474

Returns:

475

tuple: (radii, intensities) arrays

476

"""

477

478

def fit_radialprofile(radii, intensities, model_func):

479

"""

480

Fit model to radial profile.

481

482

Parameters:

483

- radii: numpy.ndarray, radial coordinates

484

- intensities: numpy.ndarray, intensity values

485

- model_func: callable, fitting function

486

487

Returns:

488

dict: Fitted parameters and statistics

489

"""

490

491

def run_singleImage(image, center_guess=None):

492

"""

493

Complete radial profile analysis for single image.

494

495

Parameters:

496

- image: numpy.ndarray, input image

497

- center_guess: tuple, initial center guess

498

499

Returns:

500

dict: Analysis results including profile and fits

501

"""

502

```

503

504

### Local Maxima Detection

505

506

Functions for finding local intensity maxima in images.

507

508

```python { .api }

509

def local_max(image, min_distance=1, threshold_abs=None):

510

"""

511

Find local maxima in image.

512

513

Parameters:

514

- image: numpy.ndarray, input image

515

- min_distance: int, minimum distance between maxima

516

- threshold_abs: float, absolute intensity threshold

517

518

Returns:

519

numpy.ndarray: Coordinates of local maxima

520

"""

521

```

522

523

## Usage Examples

524

525

### Image Alignment

526

527

```python

528

import ncempy.algo as algo

529

530

# Align two images using cross-correlation

531

reference = data1['data']

532

moving = data2['data']

533

aligned = algo.image_correlate(moving, reference)

534

535

# Align entire image stack

536

stack = image_series # 3D array (frames, y, x)

537

aligned_stack = algo.stack_align(stack)

538

```

539

540

### Peak Detection and Analysis

541

542

```python

543

import ncempy.algo as algo

544

545

# Find peaks in diffraction pattern

546

peaks = algo.peakFind2D(diffraction_image, sigma=2, threshold=0.1)

547

548

# Generate theoretical lattice

549

lattice_params = {'a': 5.0, 'b': 5.0, 'angle': 90.0}

550

theoretical = algo.lattice2D(peaks[:10], lattice_params)

551

552

# Refine lattice parameters

553

refined_params = algo.refineLattice2D(peaks, lattice_params)

554

```

555

556

### Gaussian Fitting

557

558

```python

559

import ncempy.algo as algo

560

561

# Fit 2D Gaussian to peaks

562

fitted_peaks = algo.fit_peaks_gauss2d(image, peak_positions)

563

564

# Extract peak parameters

565

for i, peak in enumerate(fitted_peaks):

566

print(f"Peak {i}: amplitude={peak['amplitude']:.3f}")

567

```