A series of convenience functions to make basic image processing functions such as translation, rotation, resizing, skeletonization, displaying Matplotlib images, sorting contours, detecting edges, and much more easier with OpenCV and both Python 2.7 and Python 3.
npx @tessl/cli install tessl/pypi-imutils@0.5.00
# imutils
1
2
A comprehensive collection of convenience functions that simplify common image processing and computer vision operations using OpenCV. The library provides streamlined implementations for image transformations, morphological operations, edge detection, contour processing, video streaming utilities, and display helpers for Matplotlib integration.
3
4
## Package Information
5
6
- **Package Name**: imutils
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install imutils`
10
- **Version**: 0.5.4
11
- **License**: MIT
12
- **Documentation**: http://www.pyimagesearch.com
13
14
## Core Imports
15
16
```python
17
import imutils
18
```
19
20
For specific functionality:
21
22
```python
23
from imutils import resize, rotate, translate
24
from imutils.video import VideoStream, FPS
25
from imutils.face_utils import FaceAligner, rect_to_bb
26
from imutils.feature import RootSIFT
27
```
28
29
## Basic Usage
30
31
```python
32
import cv2
33
import imutils
34
35
# Load an image
36
image = cv2.imread("example.jpg")
37
38
# Basic image transformations
39
resized = imutils.resize(image, width=300)
40
rotated = imutils.rotate(image, 45)
41
translated = imutils.translate(image, 25, -75)
42
43
# Edge detection with automatic thresholding
44
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
45
edges = imutils.auto_canny(gray)
46
47
# Video stream processing
48
vs = VideoStream(src=0).start()
49
fps = FPS().start()
50
51
while True:
52
frame = vs.read()
53
if frame is None:
54
break
55
56
# Process frame here
57
processed = imutils.resize(frame, width=400)
58
59
fps.update()
60
cv2.imshow("Frame", processed)
61
62
if cv2.waitKey(1) & 0xFF == ord('q'):
63
break
64
65
fps.stop()
66
vs.stop()
67
cv2.destroyAllWindows()
68
```
69
70
## Architecture
71
72
The imutils library is organized into functional modules:
73
74
- **Core Functions**: Basic image transformations and utilities in the main module
75
- **Video Processing**: Threaded video capture and FPS monitoring classes
76
- **Face Utilities**: Facial landmark processing and face alignment tools
77
- **Feature Detection**: OpenCV-compatible feature detectors and descriptors
78
- **Specialized Utilities**: Contour sorting, perspective transforms, text rendering, encodings
79
80
This modular design enables selective import of functionality while maintaining consistent APIs across OpenCV versions and Python 2/3 compatibility.
81
82
## Capabilities
83
84
### Core Image Processing
85
86
Essential image transformation and processing functions including resize with aspect ratio preservation, rotation, translation, skeletonization, automatic edge detection, and OpenCV version compatibility utilities.
87
88
```python { .api }
89
def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
90
"""Resize image maintaining aspect ratio"""
91
92
def rotate(image, angle, center=None, scale=1.0):
93
"""Rotate image around center point"""
94
95
def rotate_bound(image, angle):
96
"""Rotate image with automatic boundary adjustment"""
97
98
def translate(image, x, y):
99
"""Translate image by x, y pixels"""
100
101
def auto_canny(image, sigma=0.33):
102
"""Automatic Canny edge detection using median-based thresholds"""
103
104
def skeletonize(image, size, structuring=cv2.MORPH_RECT):
105
"""Skeletonize binary image using morphological operations"""
106
```
107
108
[Core Image Processing](./core-processing.md)
109
110
### Video Stream Processing
111
112
Threaded video capture classes for efficient real-time processing with webcams, video files, and Raspberry Pi cameras. Includes FPS monitoring and unified streaming interface.
113
114
```python { .api }
115
class VideoStream:
116
def __init__(self, src=0, usePiCamera=False, resolution=(320, 240), framerate=32, **kwargs):
117
"""Unified video stream interface"""
118
119
def start(self): ...
120
def read(self): ...
121
def stop(self): ...
122
123
class FPS:
124
def __init__(self): ...
125
def start(self): ...
126
def update(self): ...
127
def fps(self): ...
128
```
129
130
[Video Processing](./video-processing.md)
131
132
### Face Analysis Utilities
133
134
Facial landmark processing tools and face alignment functionality for dlib-based face detection workflows. Includes coordinate conversion and visualization utilities.
135
136
```python { .api }
137
class FaceAligner:
138
def __init__(self, predictor, desiredLeftEye=(0.35, 0.35), desiredFaceWidth=256, desiredFaceHeight=None):
139
"""Face alignment based on eye positions"""
140
141
def align(self, image, gray, rect):
142
"""Align and crop face"""
143
144
def rect_to_bb(rect):
145
"""Convert dlib rectangle to OpenCV bounding box"""
146
147
def shape_to_np(shape, dtype="int"):
148
"""Convert dlib shape to numpy array"""
149
```
150
151
[Face Analysis](./face-analysis.md)
152
153
### Feature Detection
154
155
OpenCV-compatible feature detectors and descriptors with cross-version compatibility. Includes factory functions and enhanced descriptors like RootSIFT.
156
157
```python { .api }
158
def FeatureDetector_create(detector, *args, **kwargs):
159
"""Create feature detector with cross-version compatibility"""
160
161
def DescriptorExtractor_create(extractor, *args, **kwargs):
162
"""Create descriptor extractor with cross-version compatibility"""
163
164
class RootSIFT:
165
def __init__(self): ...
166
def compute(self, image, kps, eps=1e-7): ...
167
```
168
169
[Feature Detection](./feature-detection.md)
170
171
### Utility Functions
172
173
Specialized utilities for contour processing, perspective transforms, path handling, text rendering, image encoding, and temporary file management.
174
175
```python { .api }
176
def sort_contours(cnts, method="left-to-right"):
177
"""Sort contours by position"""
178
179
def four_point_transform(image, pts):
180
"""Apply perspective transform for bird's eye view"""
181
182
def non_max_suppression(boxes, probs=None, overlapThresh=0.3):
183
"""Apply non-maximum suppression to bounding boxes"""
184
185
def list_images(basePath, contains=None):
186
"""List image files in directory"""
187
```
188
189
[Utility Functions](./utilities.md)
190
191
## Version Compatibility
192
193
```python { .api }
194
def is_cv2(or_better=False):
195
"""Check if OpenCV version is 2.x"""
196
197
def is_cv3(or_better=False):
198
"""Check if OpenCV version is 3.x"""
199
200
def is_cv4(or_better=False):
201
"""Check if OpenCV version is 4.x"""
202
203
def grab_contours(cnts):
204
"""Extract contours from cv2.findContours (cross-version compatibility)"""
205
```
206
207
## Types
208
209
```python { .api }
210
# Package version
211
__version__: str # Package version string (e.g., "0.5.4")
212
213
# Common parameter types used throughout the library
214
ImageArray = np.ndarray # OpenCV image as numpy array
215
Point2D = Tuple[int, int] # (x, y) coordinate pair
216
BoundingBox = Tuple[int, int, int, int] # (x, y, width, height)
217
Color = Tuple[int, int, int] # (B, G, R) color tuple
218
Contour = np.ndarray # Contour points as numpy array
219
```