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.0A 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.
pip install imutilsimport imutilsFor specific functionality:
from imutils import resize, rotate, translate
from imutils.video import VideoStream, FPS
from imutils.face_utils import FaceAligner, rect_to_bb
from imutils.feature import RootSIFTimport cv2
import imutils
# Load an image
image = cv2.imread("example.jpg")
# Basic image transformations
resized = imutils.resize(image, width=300)
rotated = imutils.rotate(image, 45)
translated = imutils.translate(image, 25, -75)
# Edge detection with automatic thresholding
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
edges = imutils.auto_canny(gray)
# Video stream processing
vs = VideoStream(src=0).start()
fps = FPS().start()
while True:
frame = vs.read()
if frame is None:
break
# Process frame here
processed = imutils.resize(frame, width=400)
fps.update()
cv2.imshow("Frame", processed)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
fps.stop()
vs.stop()
cv2.destroyAllWindows()The imutils library is organized into functional modules:
This modular design enables selective import of functionality while maintaining consistent APIs across OpenCV versions and Python 2/3 compatibility.
Essential image transformation and processing functions including resize with aspect ratio preservation, rotation, translation, skeletonization, automatic edge detection, and OpenCV version compatibility utilities.
def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
"""Resize image maintaining aspect ratio"""
def rotate(image, angle, center=None, scale=1.0):
"""Rotate image around center point"""
def rotate_bound(image, angle):
"""Rotate image with automatic boundary adjustment"""
def translate(image, x, y):
"""Translate image by x, y pixels"""
def auto_canny(image, sigma=0.33):
"""Automatic Canny edge detection using median-based thresholds"""
def skeletonize(image, size, structuring=cv2.MORPH_RECT):
"""Skeletonize binary image using morphological operations"""Threaded video capture classes for efficient real-time processing with webcams, video files, and Raspberry Pi cameras. Includes FPS monitoring and unified streaming interface.
class VideoStream:
def __init__(self, src=0, usePiCamera=False, resolution=(320, 240), framerate=32, **kwargs):
"""Unified video stream interface"""
def start(self): ...
def read(self): ...
def stop(self): ...
class FPS:
def __init__(self): ...
def start(self): ...
def update(self): ...
def fps(self): ...Facial landmark processing tools and face alignment functionality for dlib-based face detection workflows. Includes coordinate conversion and visualization utilities.
class FaceAligner:
def __init__(self, predictor, desiredLeftEye=(0.35, 0.35), desiredFaceWidth=256, desiredFaceHeight=None):
"""Face alignment based on eye positions"""
def align(self, image, gray, rect):
"""Align and crop face"""
def rect_to_bb(rect):
"""Convert dlib rectangle to OpenCV bounding box"""
def shape_to_np(shape, dtype="int"):
"""Convert dlib shape to numpy array"""OpenCV-compatible feature detectors and descriptors with cross-version compatibility. Includes factory functions and enhanced descriptors like RootSIFT.
def FeatureDetector_create(detector, *args, **kwargs):
"""Create feature detector with cross-version compatibility"""
def DescriptorExtractor_create(extractor, *args, **kwargs):
"""Create descriptor extractor with cross-version compatibility"""
class RootSIFT:
def __init__(self): ...
def compute(self, image, kps, eps=1e-7): ...Specialized utilities for contour processing, perspective transforms, path handling, text rendering, image encoding, and temporary file management.
def sort_contours(cnts, method="left-to-right"):
"""Sort contours by position"""
def four_point_transform(image, pts):
"""Apply perspective transform for bird's eye view"""
def non_max_suppression(boxes, probs=None, overlapThresh=0.3):
"""Apply non-maximum suppression to bounding boxes"""
def list_images(basePath, contains=None):
"""List image files in directory"""def is_cv2(or_better=False):
"""Check if OpenCV version is 2.x"""
def is_cv3(or_better=False):
"""Check if OpenCV version is 3.x"""
def is_cv4(or_better=False):
"""Check if OpenCV version is 4.x"""
def grab_contours(cnts):
"""Extract contours from cv2.findContours (cross-version compatibility)"""# Package version
__version__: str # Package version string (e.g., "0.5.4")
# Common parameter types used throughout the library
ImageArray = np.ndarray # OpenCV image as numpy array
Point2D = Tuple[int, int] # (x, y) coordinate pair
BoundingBox = Tuple[int, int, int, int] # (x, y, width, height)
Color = Tuple[int, int, int] # (B, G, R) color tuple
Contour = np.ndarray # Contour points as numpy array