or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

color-management.mdcolor-utilities.mdcore-image.mddrawing.mdenhancement.mdfilters.mdfonts.mdimage-sequences.mdimage-statistics.mdindex.mdmath-operations.mdoperations.md

filters.mddocs/

0

# Image Filters

1

2

Comprehensive filtering system for image enhancement, blur effects, edge detection, and artistic effects. The ImageFilter module provides both built-in filters and the capability to create custom filters for advanced image processing.

3

4

## Capabilities

5

6

### Filter Base Classes

7

8

Base classes for creating and using image filters.

9

10

```python { .api }

11

class Filter:

12

"""Abstract base class for all image filters."""

13

14

class MultibandFilter(Filter):

15

"""Base class for filters that can be applied to multi-band images."""

16

17

class BuiltinFilter(MultibandFilter):

18

"""Base class for built-in C-implemented filters."""

19

20

class Kernel(BuiltinFilter):

21

"""Convolution kernel filter for custom filtering operations."""

22

23

def __init__(self, size, kernel, scale=None, offset=0):

24

"""

25

Create a convolution kernel filter.

26

27

Parameters:

28

- size (tuple): Kernel size as (width, height)

29

- kernel (sequence): Kernel values (length must equal width * height)

30

- scale (float): Scale factor for kernel values

31

- offset (int): Offset added to convolution result

32

"""

33

34

class RankFilter(Filter):

35

"""Base class for rank-based filters that work on pixel neighborhoods."""

36

37

def __init__(self, size, rank):

38

"""

39

Create a rank filter.

40

41

Parameters:

42

- size (int): Neighborhood size (must be odd)

43

- rank (int): Rank within neighborhood (0 to size²-1)

44

"""

45

```

46

47

### Blur Filters

48

49

Various blur and smoothing effects.

50

51

```python { .api }

52

class GaussianBlur(MultibandFilter):

53

"""Gaussian blur filter with configurable radius."""

54

55

def __init__(self, radius=2):

56

"""

57

Create a Gaussian blur filter.

58

59

Parameters:

60

- radius (float): Blur radius in pixels

61

"""

62

63

class BoxBlur(MultibandFilter):

64

"""Box blur filter providing uniform averaging."""

65

66

def __init__(self, radius):

67

"""

68

Create a box blur filter.

69

70

Parameters:

71

- radius (float): Blur radius in pixels

72

"""

73

74

class MotionBlur(BuiltinFilter):

75

"""Motion blur filter simulating camera or object movement."""

76

77

def __init__(self, size, angle):

78

"""

79

Create a motion blur filter.

80

81

Parameters:

82

- size (float): Length of blur in pixels

83

- angle (float): Angle of motion in degrees

84

"""

85

86

# Built-in blur filter instances

87

BLUR: BuiltinFilter # Standard blur filter

88

SMOOTH: BuiltinFilter # Light smoothing filter

89

SMOOTH_MORE: BuiltinFilter # Strong smoothing filter

90

```

91

92

### Sharpening Filters

93

94

Filters for enhancing image sharpness and detail.

95

96

```python { .api }

97

class UnsharpMask(MultibandFilter):

98

"""Unsharp mask filter for advanced sharpening control."""

99

100

def __init__(self, radius=2, percent=150, threshold=3):

101

"""

102

Create an unsharp mask filter.

103

104

Parameters:

105

- radius (float): Blur radius for mask creation

106

- percent (int): Sharpening strength as percentage

107

- threshold (int): Minimum difference for sharpening to be applied

108

"""

109

110

# Built-in sharpening filter instances

111

SHARPEN: BuiltinFilter # Standard sharpening filter

112

DETAIL: BuiltinFilter # Detail enhancement filter

113

```

114

115

### Edge Detection Filters

116

117

Filters for detecting and enhancing edges in images.

118

119

```python { .api }

120

# Built-in edge detection filter instances

121

FIND_EDGES: BuiltinFilter # Edge detection filter

122

EDGE_ENHANCE: BuiltinFilter # Light edge enhancement

123

EDGE_ENHANCE_MORE: BuiltinFilter # Strong edge enhancement

124

CONTOUR: BuiltinFilter # Contour detection filter

125

```

126

127

### Artistic Effect Filters

128

129

Filters for creating artistic and stylistic effects.

130

131

```python { .api }

132

# Built-in artistic effect filter instances

133

EMBOSS: BuiltinFilter # Emboss effect filter

134

```

135

136

### Rank Filters

137

138

Filters based on pixel ranking in neighborhoods.

139

140

```python { .api }

141

class MedianFilter(RankFilter):

142

"""Median filter for noise reduction while preserving edges."""

143

144

def __init__(self, size=3):

145

"""

146

Create a median filter.

147

148

Parameters:

149

- size (int): Filter size (must be odd, typically 3, 5, or 7)

150

"""

151

152

class MinFilter(RankFilter):

153

"""Minimum filter - selects darkest pixel in neighborhood."""

154

155

def __init__(self, size=3):

156

"""

157

Create a minimum filter.

158

159

Parameters:

160

- size (int): Filter size (must be odd)

161

"""

162

163

class MaxFilter(RankFilter):

164

"""Maximum filter - selects brightest pixel in neighborhood."""

165

166

def __init__(self, size=3):

167

"""

168

Create a maximum filter.

169

170

Parameters:

171

- size (int): Filter size (must be odd)

172

"""

173

174

class ModeFilter(Filter):

175

"""Mode filter - selects most common pixel value in neighborhood."""

176

177

def __init__(self, size=3):

178

"""

179

Create a mode filter.

180

181

Parameters:

182

- size (int): Filter size (must be odd)

183

"""

184

```

185

186

### Applying Filters

187

188

Methods for applying filters to images.

189

190

```python { .api }

191

class Image:

192

def filter(self, filter):

193

"""

194

Apply a filter to the image.

195

196

Parameters:

197

- filter (Filter): Filter instance to apply

198

199

Returns:

200

Image: Filtered image

201

"""

202

```

203

204

## Usage Examples

205

206

### Basic Filter Application

207

208

```python

209

from PIL import Image, ImageFilter

210

211

# Open an image

212

img = Image.open("photo.jpg")

213

214

# Apply various built-in filters

215

blurred = img.filter(ImageFilter.BLUR)

216

sharpened = img.filter(ImageFilter.SHARPEN)

217

edges = img.filter(ImageFilter.FIND_EDGES)

218

embossed = img.filter(ImageFilter.EMBOSS)

219

220

# Save results

221

blurred.save("blurred.jpg")

222

sharpened.save("sharpened.jpg")

223

edges.save("edges.jpg")

224

embossed.save("embossed.jpg")

225

```

226

227

### Advanced Blur Effects

228

229

```python

230

from PIL import Image, ImageFilter

231

232

img = Image.open("portrait.jpg")

233

234

# Different blur techniques

235

gaussian_light = img.filter(ImageFilter.GaussianBlur(radius=1))

236

gaussian_heavy = img.filter(ImageFilter.GaussianBlur(radius=5))

237

box_blur = img.filter(ImageFilter.BoxBlur(radius=3))

238

239

# Motion blur for dynamic effect

240

motion_blur = img.filter(ImageFilter.MotionBlur(size=10, angle=45))

241

242

# Save variations

243

gaussian_light.save("light_blur.jpg")

244

gaussian_heavy.save("heavy_blur.jpg")

245

box_blur.save("box_blur.jpg")

246

motion_blur.save("motion_blur.jpg")

247

```

248

249

### Noise Reduction and Cleanup

250

251

```python

252

from PIL import Image, ImageFilter

253

254

# Load a noisy image

255

noisy_img = Image.open("noisy_photo.jpg")

256

257

# Apply median filter to reduce noise while preserving edges

258

denoised = noisy_img.filter(ImageFilter.MedianFilter(size=3))

259

260

# For heavy noise, use larger kernel

261

heavily_denoised = noisy_img.filter(ImageFilter.MedianFilter(size=5))

262

263

# Minimum filter to reduce bright noise

264

min_filtered = noisy_img.filter(ImageFilter.MinFilter(size=3))

265

266

# Maximum filter to reduce dark noise

267

max_filtered = noisy_img.filter(ImageFilter.MaxFilter(size=3))

268

269

denoised.save("denoised.jpg")

270

heavily_denoised.save("heavily_denoised.jpg")

271

```

272

273

### Professional Sharpening

274

275

```python

276

from PIL import Image, ImageFilter

277

278

img = Image.open("soft_photo.jpg")

279

280

# Basic sharpening

281

basic_sharp = img.filter(ImageFilter.SHARPEN)

282

283

# Advanced unsharp mask for professional results

284

# Subtle sharpening for portraits

285

portrait_sharp = img.filter(ImageFilter.UnsharpMask(radius=1, percent=100, threshold=3))

286

287

# Strong sharpening for landscapes

288

landscape_sharp = img.filter(ImageFilter.UnsharpMask(radius=2, percent=200, threshold=2))

289

290

# Extreme sharpening for special effects

291

extreme_sharp = img.filter(ImageFilter.UnsharpMask(radius=3, percent=300, threshold=1))

292

293

basic_sharp.save("basic_sharp.jpg")

294

portrait_sharp.save("portrait_sharp.jpg")

295

landscape_sharp.save("landscape_sharp.jpg")

296

extreme_sharp.save("extreme_sharp.jpg")

297

```

298

299

### Custom Convolution Kernels

300

301

```python

302

from PIL import Image, ImageFilter

303

304

img = Image.open("test_image.jpg")

305

306

# Custom edge detection kernel

307

edge_kernel = ImageFilter.Kernel(

308

size=(3, 3),

309

kernel=[-1, -1, -1,

310

-1, 8, -1,

311

-1, -1, -1],

312

scale=1,

313

offset=0

314

)

315

316

# Custom sharpening kernel

317

sharpen_kernel = ImageFilter.Kernel(

318

size=(3, 3),

319

kernel=[ 0, -1, 0,

320

-1, 5, -1,

321

0, -1, 0],

322

scale=1,

323

offset=0

324

)

325

326

# Custom blur kernel

327

blur_kernel = ImageFilter.Kernel(

328

size=(3, 3),

329

kernel=[1, 1, 1,

330

1, 1, 1,

331

1, 1, 1],

332

scale=9, # Normalize by sum of kernel values

333

offset=0

334

)

335

336

# Apply custom kernels

337

edge_detected = img.filter(edge_kernel)

338

custom_sharpened = img.filter(sharpen_kernel)

339

custom_blurred = img.filter(blur_kernel)

340

341

edge_detected.save("custom_edges.jpg")

342

custom_sharpened.save("custom_sharpened.jpg")

343

custom_blurred.save("custom_blurred.jpg")

344

```

345

346

### Filter Combinations and Workflows

347

348

```python

349

from PIL import Image, ImageFilter

350

351

def enhance_photo(img):

352

"""Professional photo enhancement pipeline."""

353

# Step 1: Noise reduction

354

cleaned = img.filter(ImageFilter.MedianFilter(size=3))

355

356

# Step 2: Gentle sharpening

357

sharpened = cleaned.filter(ImageFilter.UnsharpMask(radius=1.5, percent=120, threshold=3))

358

359

# Step 3: Edge enhancement

360

enhanced = sharpened.filter(ImageFilter.EDGE_ENHANCE)

361

362

return enhanced

363

364

def artistic_effect(img):

365

"""Create artistic effect by combining filters."""

366

# Apply emboss effect

367

embossed = img.filter(ImageFilter.EMBOSS)

368

369

# Slight blur to soften harsh edges

370

softened = embossed.filter(ImageFilter.GaussianBlur(radius=0.5))

371

372

return softened

373

374

# Process images

375

original = Image.open("landscape.jpg")

376

enhanced = enhance_photo(original)

377

artistic = artistic_effect(original)

378

379

enhanced.save("enhanced_landscape.jpg")

380

artistic.save("artistic_landscape.jpg")

381

```

382

383

### Filter Strength Comparison

384

385

```python

386

from PIL import Image, ImageFilter

387

388

def create_filter_comparison(img, output_path):

389

"""Create a comparison of different filter strengths."""

390

width, height = img.size

391

392

# Create comparison image (2x3 grid)

393

comparison = Image.new("RGB", (width * 3, height * 2), "white")

394

395

# Original and variations

396

filters_and_labels = [

397

(None, "Original"),

398

(ImageFilter.GaussianBlur(1), "Light Blur"),

399

(ImageFilter.GaussianBlur(3), "Heavy Blur"),

400

(ImageFilter.SHARPEN, "Sharpened"),

401

(ImageFilter.UnsharpMask(radius=2, percent=200, threshold=2), "Unsharp Mask"),

402

(ImageFilter.FIND_EDGES, "Edge Detection")

403

]

404

405

for i, (filter_obj, label) in enumerate(filters_and_labels):

406

# Apply filter

407

if filter_obj is None:

408

filtered = img

409

else:

410

filtered = img.filter(filter_obj)

411

412

# Calculate position in grid

413

col = i % 3

414

row = i // 3

415

x = col * width

416

y = row * height

417

418

# Paste filtered image

419

comparison.paste(filtered, (x, y))

420

421

comparison.save(output_path)

422

423

# Create comparison

424

img = Image.open("sample.jpg")

425

create_filter_comparison(img, "filter_comparison.jpg")

426

```

427

428

### Working with Different Image Modes

429

430

```python

431

from PIL import Image, ImageFilter

432

433

# Load images in different modes

434

rgb_img = Image.open("color_photo.jpg") # RGB mode

435

grayscale_img = Image.open("bw_photo.jpg").convert("L") # L mode

436

rgba_img = Image.open("logo.png") # RGBA mode

437

438

# Apply filters appropriate for each mode

439

# RGB - all filters work

440

rgb_filtered = rgb_img.filter(ImageFilter.GaussianBlur(2))

441

442

# Grayscale - efficient for single-channel operations

443

gray_sharpened = grayscale_img.filter(ImageFilter.SHARPEN)

444

445

# RGBA - preserve alpha channel

446

if rgba_img.mode == "RGBA":

447

# Split into RGB and alpha

448

rgb_part = rgba_img.convert("RGB")

449

alpha_part = rgba_img.split()[-1]

450

451

# Apply filter to RGB part only

452

filtered_rgb = rgb_part.filter(ImageFilter.GaussianBlur(1))

453

454

# Recombine with original alpha

455

filtered_rgba = Image.merge("RGBA", filtered_rgb.split() + [alpha_part])

456

else:

457

filtered_rgba = rgba_img.filter(ImageFilter.GaussianBlur(1))

458

459

rgb_filtered.save("rgb_filtered.jpg")

460

gray_sharpened.save("gray_sharpened.jpg")

461

filtered_rgba.save("rgba_filtered.png")

462

```