0
# Core Image Processing
1
2
Essential image transformation and processing functions that provide convenient wrappers around OpenCV operations. These functions handle common computer vision tasks with simplified APIs and automatic parameter handling.
3
4
## Capabilities
5
6
### Image Resizing
7
8
Resizes images while maintaining aspect ratio. Automatically calculates missing dimension and supports different interpolation methods.
9
10
```python { .api }
11
def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
12
"""
13
Resize image maintaining aspect ratio.
14
15
Args:
16
image (np.ndarray): Input image
17
width (int, optional): Target width in pixels
18
height (int, optional): Target height in pixels
19
inter (int): OpenCV interpolation method (default: cv2.INTER_AREA)
20
21
Returns:
22
np.ndarray: Resized image
23
24
Note:
25
If both width and height are None, returns original image.
26
If only width is provided, height is calculated to maintain aspect ratio.
27
If only height is provided, width is calculated to maintain aspect ratio.
28
"""
29
```
30
31
**Usage Example:**
32
```python
33
import cv2
34
import imutils
35
36
image = cv2.imread("example.jpg")
37
38
# Resize to width of 300 pixels (height calculated automatically)
39
resized = imutils.resize(image, width=300)
40
41
# Resize to height of 200 pixels (width calculated automatically)
42
resized = imutils.resize(image, height=200)
43
44
# Use different interpolation
45
resized = imutils.resize(image, width=400, inter=cv2.INTER_CUBIC)
46
```
47
48
### Image Rotation
49
50
Rotates images around a specified center point with optional scaling. Provides both standard rotation and boundary-adjusted rotation.
51
52
```python { .api }
53
def rotate(image, angle, center=None, scale=1.0):
54
"""
55
Rotate image around center point.
56
57
Args:
58
image (np.ndarray): Input image
59
angle (float): Rotation angle in degrees (positive = counterclockwise)
60
center (tuple, optional): (x, y) rotation center (default: image center)
61
scale (float): Scaling factor (default: 1.0)
62
63
Returns:
64
np.ndarray: Rotated image (same dimensions as input)
65
"""
66
67
def rotate_bound(image, angle):
68
"""
69
Rotate image with automatic boundary adjustment to prevent clipping.
70
71
Args:
72
image (np.ndarray): Input image
73
angle (float): Rotation angle in degrees
74
75
Returns:
76
np.ndarray: Rotated image with adjusted dimensions
77
"""
78
```
79
80
**Usage Example:**
81
```python
82
import cv2
83
import imutils
84
85
image = cv2.imread("example.jpg")
86
87
# Standard rotation (may clip corners)
88
rotated = imutils.rotate(image, 45)
89
90
# Rotation with custom center and scaling
91
center = (image.shape[1] // 4, image.shape[0] // 4)
92
rotated = imutils.rotate(image, 30, center=center, scale=0.8)
93
94
# Rotation with boundary adjustment (no clipping)
95
rotated_bound = imutils.rotate_bound(image, 45)
96
```
97
98
### Image Translation
99
100
Translates (shifts) images by specified pixel offsets.
101
102
```python { .api }
103
def translate(image, x, y):
104
"""
105
Translate image by x, y pixels.
106
107
Args:
108
image (np.ndarray): Input image
109
x (int): Horizontal translation (positive = right)
110
y (int): Vertical translation (positive = down)
111
112
Returns:
113
np.ndarray: Translated image
114
"""
115
```
116
117
**Usage Example:**
118
```python
119
import cv2
120
import imutils
121
122
image = cv2.imread("example.jpg")
123
124
# Shift image 25 pixels right and 75 pixels up
125
translated = imutils.translate(image, 25, -75)
126
```
127
128
### Automatic Edge Detection
129
130
Performs automatic Canny edge detection using median-based threshold calculation.
131
132
```python { .api }
133
def auto_canny(image, sigma=0.33):
134
"""
135
Automatic Canny edge detection using median-based thresholds.
136
137
Args:
138
image (np.ndarray): Grayscale input image
139
sigma (float): Threshold sensitivity factor (default: 0.33)
140
141
Returns:
142
np.ndarray: Binary edge image
143
144
Note:
145
Automatically calculates lower and upper thresholds based on image median.
146
Lower threshold = max(0, (1.0 - sigma) * median)
147
Upper threshold = min(255, (1.0 + sigma) * median)
148
"""
149
```
150
151
**Usage Example:**
152
```python
153
import cv2
154
import imutils
155
156
image = cv2.imread("example.jpg")
157
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
158
159
# Automatic edge detection
160
edges = imutils.auto_canny(gray)
161
162
# More sensitive edge detection
163
edges_sensitive = imutils.auto_canny(gray, sigma=0.2)
164
165
# Less sensitive edge detection
166
edges_coarse = imutils.auto_canny(gray, sigma=0.5)
167
```
168
169
### Image Skeletonization
170
171
Performs morphological skeletonization on binary images.
172
173
```python { .api }
174
def skeletonize(image, size, structuring=cv2.MORPH_RECT):
175
"""
176
Skeletonize binary image using morphological operations.
177
178
Args:
179
image (np.ndarray): Binary input image
180
size (tuple): (width, height) of structuring element
181
structuring (int): OpenCV morphological shape (default: cv2.MORPH_RECT)
182
183
Returns:
184
np.ndarray: Skeletonized binary image
185
"""
186
```
187
188
**Usage Example:**
189
```python
190
import cv2
191
import imutils
192
193
# Load and binarize image
194
image = cv2.imread("example.jpg", cv2.IMREAD_GRAYSCALE)
195
_, binary = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)
196
197
# Skeletonize with rectangular structuring element
198
skeleton = imutils.skeletonize(binary, (3, 3))
199
200
# Skeletonize with elliptical structuring element
201
skeleton_ellipse = imutils.skeletonize(binary, (5, 5), cv2.MORPH_ELLIPSE)
202
```
203
204
### Color Space Conversion
205
206
Converts images between OpenCV (BGR) and Matplotlib (RGB) color formats.
207
208
```python { .api }
209
def opencv2matplotlib(image):
210
"""
211
Convert OpenCV BGR image to Matplotlib RGB format.
212
213
Args:
214
image (np.ndarray): BGR image from OpenCV
215
216
Returns:
217
np.ndarray: RGB image for Matplotlib display
218
"""
219
```
220
221
**Usage Example:**
222
```python
223
import cv2
224
import imutils
225
import matplotlib.pyplot as plt
226
227
image = cv2.imread("example.jpg")
228
229
# Convert for matplotlib display
230
rgb_image = imutils.opencv2matplotlib(image)
231
232
plt.figure(figsize=(10, 6))
233
plt.imshow(rgb_image)
234
plt.axis('off')
235
plt.show()
236
```
237
238
### URL Image Loading
239
240
Downloads and loads images directly from URLs.
241
242
```python { .api }
243
def url_to_image(url, readFlag=cv2.IMREAD_COLOR):
244
"""
245
Download and load image from URL.
246
247
Args:
248
url (str): Image URL
249
readFlag (int): OpenCV read flag (default: cv2.IMREAD_COLOR)
250
251
Returns:
252
np.ndarray: Loaded image
253
"""
254
```
255
256
**Usage Example:**
257
```python
258
import imutils
259
260
# Download and load color image
261
url = "https://example.com/image.jpg"
262
image = imutils.url_to_image(url)
263
264
# Download as grayscale
265
gray_image = imutils.url_to_image(url, cv2.IMREAD_GRAYSCALE)
266
```
267
268
### Brightness and Contrast Adjustment
269
270
Adjusts image brightness and contrast using OpenCV's addWeighted function.
271
272
```python { .api }
273
def adjust_brightness_contrast(image, brightness=0., contrast=0.):
274
"""
275
Adjust image brightness and contrast.
276
277
Args:
278
image (np.ndarray): Input image
279
brightness (float): Brightness adjustment (0 = no change)
280
contrast (float): Contrast adjustment (0 = no change)
281
282
Returns:
283
np.ndarray: Adjusted image
284
"""
285
```
286
287
**Usage Example:**
288
```python
289
import cv2
290
import imutils
291
292
image = cv2.imread("example.jpg")
293
294
# Increase brightness by 20 and contrast by 10%
295
bright = imutils.adjust_brightness_contrast(image, brightness=20, contrast=10)
296
297
# Decrease brightness and increase contrast
298
adjusted = imutils.adjust_brightness_contrast(image, brightness=-15, contrast=25)
299
```
300
301
### Image Montage Creation
302
303
Creates image montages (grids) from lists of images.
304
305
```python { .api }
306
def build_montages(image_list, image_shape, montage_shape):
307
"""
308
Create image montages from list of images.
309
310
Args:
311
image_list (list): List of input images (numpy arrays)
312
image_shape (tuple): (width, height) for individual images in montage
313
montage_shape (tuple): (columns, rows) of montage grid
314
315
Returns:
316
list: List of montage images (numpy arrays)
317
318
Note:
319
Each montage is filled left-to-right, top-to-bottom.
320
Incomplete montages are filled with black pixels.
321
New montages are created when current one is full.
322
"""
323
```
324
325
**Usage Example:**
326
```python
327
import cv2
328
import imutils
329
330
# Load multiple images
331
images = [cv2.imread(f"image_{i}.jpg") for i in range(25)]
332
333
# Create 5x5 montages with 256x256 pixel images
334
montages = imutils.build_montages(images, (256, 256), (5, 5))
335
336
# Display montages
337
for i, montage in enumerate(montages):
338
cv2.imshow(f'Montage {i}', montage)
339
cv2.waitKey(0)
340
341
cv2.destroyAllWindows()
342
```
343
344
### OpenCV Version Compatibility
345
346
Utility functions for checking OpenCV version and handling cross-version compatibility.
347
348
```python { .api }
349
def is_cv2(or_better=False):
350
"""
351
Check if OpenCV version is 2.x.
352
353
Args:
354
or_better (bool): If True, check for version 2.x or higher
355
356
Returns:
357
bool: True if version matches criteria
358
"""
359
360
def is_cv3(or_better=False):
361
"""
362
Check if OpenCV version is 3.x.
363
364
Args:
365
or_better (bool): If True, check for version 3.x or higher
366
367
Returns:
368
bool: True if version matches criteria
369
"""
370
371
def is_cv4(or_better=False):
372
"""
373
Check if OpenCV version is 4.x.
374
375
Args:
376
or_better (bool): If True, check for version 4.x or higher
377
378
Returns:
379
bool: True if version matches criteria
380
"""
381
382
def get_opencv_major_version(lib=None):
383
"""
384
Get the major version number of OpenCV.
385
386
Args:
387
lib (module, optional): OpenCV module (default: imports cv2)
388
389
Returns:
390
int: Major version number (e.g., 3, 4)
391
"""
392
393
def check_opencv_version(major, lib=None):
394
"""
395
Check if OpenCV version matches major version (DEPRECATED).
396
397
Args:
398
major (str): Major version string to check (e.g., "3", "4")
399
lib (module, optional): OpenCV module (default: imports cv2)
400
401
Returns:
402
bool: True if version matches
403
404
Warning:
405
This function is deprecated and may be removed in future releases.
406
Use get_opencv_major_version() and is_cv* functions instead.
407
"""
408
409
def grab_contours(cnts):
410
"""
411
Extract contours from cv2.findContours result (cross-version compatibility).
412
413
Args:
414
cnts (tuple): Result tuple from cv2.findContours
415
416
Returns:
417
list: Contours array
418
419
Note:
420
Handles differences in cv2.findContours return format across OpenCV versions.
421
OpenCV 2.4 and 4.x return (contours, hierarchy).
422
OpenCV 3.x returns (image, contours, hierarchy).
423
"""
424
```
425
426
**Usage Example:**
427
```python
428
import cv2
429
import imutils
430
431
# Get specific version number
432
major_version = imutils.get_opencv_major_version()
433
print(f"OpenCV major version: {major_version}")
434
435
# Version checking (multiple methods)
436
if imutils.is_cv4():
437
print("Using OpenCV 4.x")
438
elif imutils.is_cv3():
439
print("Using OpenCV 3.x")
440
else:
441
print("Using older OpenCV version")
442
443
# Deprecated version checking (still works but shows warning)
444
if imutils.check_opencv_version("4"):
445
print("OpenCV 4.x detected via deprecated method")
446
447
# Cross-version contour finding
448
image = cv2.imread("example.jpg", cv2.IMREAD_GRAYSCALE)
449
cnts = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
450
cnts = imutils.grab_contours(cnts) # Works across all OpenCV versions
451
452
print(f"Found {len(cnts)} contours")
453
```
454
455
### Function Discovery
456
457
Utility for finding OpenCV functions by name pattern.
458
459
```python { .api }
460
def find_function(name, pretty_print=True, module=None):
461
"""
462
Find OpenCV functions matching name pattern.
463
464
Args:
465
name (str): Function name pattern to search for
466
pretty_print (bool): If True, print results; if False, return list
467
module: OpenCV module to search (default: cv2)
468
469
Returns:
470
list or None: List of matching function names if pretty_print=False
471
"""
472
```
473
474
**Usage Example:**
475
```python
476
import imutils
477
478
# Find all functions containing "threshold"
479
imutils.find_function("threshold")
480
481
# Get list of matching functions
482
functions = imutils.find_function("blur", pretty_print=False)
483
print(f"Found {len(functions)} blur functions")
484
```