or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-image-operations.mdfeature-detection.mdimage-filtering.mdindex.mdmorphological-operations.mdregistration-transforms.mdsegmentation.md

core-image-operations.mddocs/

0

# Core Image Operations

1

2

Essential image handling, I/O operations, and basic manipulations for medical and scientific imaging workflows using SimpleITK.

3

4

## Capabilities

5

6

### Image Input/Output

7

8

Read and write images in various medical and scientific formats.

9

10

```python { .api }

11

def ReadImage(fileName: str, imageIO: str = "") -> Image:

12

"""

13

Read an image from file

14

15

Args:

16

fileName: Path to the image file

17

imageIO: Specific ImageIO to use (optional)

18

19

Returns:

20

SimpleITK Image object

21

"""

22

23

def WriteImage(image: Image, fileName: str, useCompression: bool = False) -> None:

24

"""

25

Write an image to file

26

27

Args:

28

image: SimpleITK Image to write

29

fileName: Output file path

30

useCompression: Enable compression if supported by format

31

"""

32

```

33

34

**Usage Examples:**

35

36

```python

37

import SimpleITK as sitk

38

39

# Read various image formats

40

dicom_image = sitk.ReadImage('patient_scan.dcm')

41

nifti_image = sitk.ReadImage('brain.nii.gz')

42

png_image = sitk.ReadImage('photo.png')

43

44

# Write with compression

45

sitk.WriteImage(processed_image, 'output.nii.gz', useCompression=True)

46

47

# Specify ImageIO for ambiguous formats

48

sitk.ReadImage('data.img', imageIO='NiftiImageIO')

49

```

50

51

### NumPy Integration

52

53

Convert between SimpleITK images and NumPy arrays for scientific computing integration.

54

55

```python { .api }

56

def GetArrayFromImage(image: Image) -> np.ndarray:

57

"""

58

Convert SimpleITK Image to NumPy array

59

60

Args:

61

image: SimpleITK Image

62

63

Returns:

64

NumPy array with axes in reverse order (z,y,x for 3D)

65

"""

66

67

def GetImageFromArray(arr: np.ndarray, isVector: bool = False) -> Image:

68

"""

69

Convert NumPy array to SimpleITK Image

70

71

Args:

72

arr: NumPy array to convert

73

isVector: Whether array represents vector image

74

75

Returns:

76

SimpleITK Image with default spacing and origin

77

"""

78

79

def GetArrayViewFromImage(image: Image) -> np.ndarray:

80

"""

81

Get NumPy array view of SimpleITK Image (memory efficient)

82

83

Args:

84

image: SimpleITK Image

85

86

Returns:

87

NumPy array view sharing memory with image

88

"""

89

```

90

91

**Usage Examples:**

92

93

```python

94

import SimpleITK as sitk

95

import numpy as np

96

97

# Convert to NumPy for processing

98

image = sitk.ReadImage('input.nii')

99

array = sitk.GetArrayFromImage(image)

100

101

# Process with NumPy/SciPy

102

processed_array = np.where(array > 100, array * 2, array)

103

104

# Convert back to SimpleITK

105

processed_image = sitk.GetImageFromArray(processed_array)

106

107

# Copy image metadata

108

processed_image.CopyInformation(image)

109

sitk.WriteImage(processed_image, 'output.nii')

110

```

111

112

### Image Class

113

114

Core image representation supporting n-dimensional images with metadata.

115

116

```python { .api }

117

class Image:

118

def __init__(self, *args):

119

"""

120

Create empty image or from size/pixel type

121

122

Args:

123

width, height, [depth], pixelID: Image dimensions and pixel type

124

size: tuple of dimensions

125

pixelID: Pixel type constant

126

"""

127

128

def GetSize(self) -> tuple:

129

"""Get image dimensions as tuple"""

130

131

def GetOrigin(self) -> tuple:

132

"""Get image origin in physical coordinates"""

133

134

def GetSpacing(self) -> tuple:

135

"""Get pixel spacing in physical units"""

136

137

def GetDirection(self) -> tuple:

138

"""Get direction cosines matrix as flattened tuple"""

139

140

def GetDimension(self) -> int:

141

"""Get number of image dimensions"""

142

143

def GetPixelID(self) -> int:

144

"""Get pixel type ID"""

145

146

def GetNumberOfComponentsPerPixel(self) -> int:

147

"""Get number of components per pixel (1 for scalar, >1 for vector)"""

148

149

def GetPixelAsFloat(self, idx: tuple) -> float:

150

"""Get pixel value as float at given index"""

151

152

def SetPixelAsFloat(self, idx: tuple, value: float) -> None:

153

"""Set pixel value as float at given index"""

154

155

def GetPixelAsInt(self, idx: tuple) -> int:

156

"""Get pixel value as integer at given index"""

157

158

def SetPixelAsInt(self, idx: tuple, value: int) -> None:

159

"""Set pixel value as integer at given index"""

160

161

def CopyInformation(self, srcImage: Image) -> None:

162

"""Copy metadata (spacing, origin, direction) from another image"""

163

164

def SetOrigin(self, origin: tuple) -> None:

165

"""Set image origin in physical coordinates"""

166

167

def SetSpacing(self, spacing: tuple) -> None:

168

"""Set pixel spacing in physical units"""

169

170

def SetDirection(self, direction: tuple) -> None:

171

"""Set direction cosines matrix from flattened tuple"""

172

```

173

174

**Usage Examples:**

175

176

```python

177

import SimpleITK as sitk

178

179

# Create new image

180

image = sitk.Image(256, 256, sitk.sitkFloat32)

181

182

# Set metadata

183

image.SetOrigin((-127.5, -127.5))

184

image.SetSpacing((1.0, 1.0))

185

image.SetDirection((1, 0, 0, 1)) # 2D identity matrix

186

187

# Access pixel values

188

pixel_value = image.GetPixelAsFloat((128, 128))

189

image.SetPixelAsFloat((128, 128), 255.0)

190

191

# Get image properties

192

print(f"Size: {image.GetSize()}")

193

print(f"Spacing: {image.GetSpacing()}")

194

print(f"Origin: {image.GetOrigin()}")

195

print(f"Dimensions: {image.GetDimension()}")

196

```

197

198

### Image Information and Statistics

199

200

Get comprehensive information about images.

201

202

```python { .api }

203

def GetArrayFromImage(image: Image) -> np.ndarray:

204

"""Get image as NumPy array for statistical analysis"""

205

206

def LabelStatistics(labelImage: Image, intensityImage: Image) -> dict:

207

"""

208

Compute statistics for labeled regions

209

210

Args:

211

labelImage: Label/segmentation image

212

intensityImage: Intensity image for statistics

213

214

Returns:

215

Dictionary with statistics per label

216

"""

217

218

def StatisticsImageFilter(image: Image) -> dict:

219

"""

220

Compute basic image statistics

221

222

Args:

223

image: Input image

224

225

Returns:

226

Dictionary with min, max, mean, variance, etc.

227

"""

228

```

229

230

**Usage Examples:**

231

232

```python

233

import SimpleITK as sitk

234

235

# Load image

236

image = sitk.ReadImage('brain.nii')

237

238

# Basic statistics

239

stats_filter = sitk.StatisticsImageFilter()

240

stats_filter.Execute(image)

241

242

print(f"Min: {stats_filter.GetMinimum()}")

243

print(f"Max: {stats_filter.GetMaximum()}")

244

print(f"Mean: {stats_filter.GetMean()}")

245

print(f"Std: {stats_filter.GetSigma()}")

246

247

# Label statistics

248

labels = sitk.ReadImage('segmentation.nii')

249

label_stats = sitk.LabelStatisticsImageFilter()

250

label_stats.Execute(labels, image)

251

252

for label in label_stats.GetLabels():

253

print(f"Label {label}: mean={label_stats.GetMean(label):.2f}")

254

```

255

256

### Image Display and Visualization

257

258

Display images for debugging and analysis.

259

260

```python { .api }

261

def Show(image: Image, title: str = "", debugOn: bool = False) -> None:

262

"""

263

Display image using external viewer

264

265

Args:

266

image: SimpleITK Image to display

267

title: Window title

268

debugOn: Enable debug output

269

"""

270

```

271

272

**Usage Examples:**

273

274

```python

275

import SimpleITK as sitk

276

277

# Display images

278

image = sitk.ReadImage('input.png')

279

sitk.Show(image, title="Original Image")

280

281

# Display processed result

282

filtered = sitk.Gaussian(image, sigma=2.0)

283

sitk.Show(filtered, title="Smoothed Image")

284

```

285

286

### Image Metadata Operations

287

288

Access and modify image metadata including DICOM tags.

289

290

```python { .api }

291

def ReadImage(fileName: str) -> Image:

292

"""Read image with metadata"""

293

294

# Access metadata through Image methods

295

def HasMetaDataKey(image: Image, key: str) -> bool:

296

"""Check if metadata key exists"""

297

298

def GetMetaData(image: Image, key: str) -> str:

299

"""Get metadata value for key"""

300

301

def SetMetaData(image: Image, key: str, value: str) -> None:

302

"""Set metadata key-value pair"""

303

304

def GetMetaDataKeys(image: Image) -> list:

305

"""Get all metadata keys"""

306

```

307

308

**Usage Examples:**

309

310

```python

311

import SimpleITK as sitk

312

313

# Read DICOM with metadata

314

dicom_image = sitk.ReadImage('scan.dcm')

315

316

# Access DICOM tags

317

if dicom_image.HasMetaDataKey('0010|0010'): # Patient Name

318

patient_name = dicom_image.GetMetaData('0010|0010')

319

print(f"Patient: {patient_name}")

320

321

# List all metadata

322

for key in dicom_image.GetMetaDataKeys():

323

value = dicom_image.GetMetaData(key)

324

print(f"{key}: {value}")

325

```

326

327

### Multi-Component Images

328

329

Handle vector and multi-component images.

330

331

```python { .api }

332

def Compose(*images: Image) -> Image:

333

"""

334

Compose multiple scalar images into vector image

335

336

Args:

337

images: Scalar images to combine

338

339

Returns:

340

Multi-component vector image

341

"""

342

343

def VectorIndexSelectionCast(image: Image, index: int, outputPixelType: int) -> Image:

344

"""

345

Extract single component from vector image

346

347

Args:

348

image: Multi-component image

349

index: Component index to extract

350

outputPixelType: Output pixel type

351

352

Returns:

353

Scalar image with selected component

354

"""

355

```

356

357

**Usage Examples:**

358

359

```python

360

import SimpleITK as sitk

361

362

# Create RGB image from separate channels

363

red = sitk.ReadImage('red_channel.png')

364

green = sitk.ReadImage('green_channel.png')

365

blue = sitk.ReadImage('blue_channel.png')

366

367

rgb_image = sitk.Compose(red, green, blue)

368

sitk.WriteImage(rgb_image, 'rgb_output.png')

369

370

# Extract single channel

371

red_extracted = sitk.VectorIndexSelectionCast(rgb_image, 0, sitk.sitkUInt8)

372

```

373

374

## Pixel Types and Constants

375

376

```python { .api }

377

# Basic pixel types

378

sitkUInt8: int = 1 # 8-bit unsigned integer

379

sitkInt8: int = 2 # 8-bit signed integer

380

sitkUInt16: int = 3 # 16-bit unsigned integer

381

sitkInt16: int = 4 # 16-bit signed integer

382

sitkUInt32: int = 5 # 32-bit unsigned integer

383

sitkInt32: int = 6 # 32-bit signed integer

384

sitkFloat32: int = 8 # 32-bit floating point

385

sitkFloat64: int = 9 # 64-bit floating point

386

387

# Vector pixel types

388

sitkVectorUInt8: int = 13

389

sitkVectorFloat32: int = 16

390

sitkVectorFloat64: int = 17

391

392

# Complex pixel types

393

sitkComplexFloat32: int = 10

394

sitkComplexFloat64: int = 11

395

```

396

397

## Error Handling

398

399

SimpleITK operations can raise exceptions for invalid operations:

400

401

```python

402

import SimpleITK as sitk

403

404

try:

405

# File operations

406

image = sitk.ReadImage('nonexistent.nii')

407

except RuntimeError as e:

408

print(f"File error: {e}")

409

410

try:

411

# Pixel access

412

value = image.GetPixelAsFloat((1000, 1000)) # Out of bounds

413

except RuntimeError as e:

414

print(f"Index error: {e}")

415

416

try:

417

# Type conversion

418

float_image = sitk.Cast(int_image, sitk.sitkFloat32)

419

except RuntimeError as e:

420

print(f"Cast error: {e}")

421

```

422

423

## Performance Considerations

424

425

### Memory Management

426

427

```python

428

# Memory-efficient array views

429

array_view = sitk.GetArrayViewFromImage(large_image) # No copy

430

array_copy = sitk.GetArrayFromImage(large_image) # Full copy

431

432

# Explicit cleanup for large images

433

del large_image

434

import gc; gc.collect()

435

```

436

437

### Multi-threading

438

439

```python

440

import SimpleITK as sitk

441

442

# Configure global thread count

443

sitk.SetGlobalDefaultNumberOfThreads(8)

444

threads = sitk.GetGlobalDefaultNumberOfThreads()

445

print(f"Using {threads} threads")

446

```