CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-imutils

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.

91

1.33x
Overview
Eval results
Files

core-processing.mddocs/

Core Image Processing

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.

Capabilities

Image Resizing

Resizes images while maintaining aspect ratio. Automatically calculates missing dimension and supports different interpolation methods.

def resize(image, width=None, height=None, inter=cv2.INTER_AREA):
    """
    Resize image maintaining aspect ratio.
    
    Args:
        image (np.ndarray): Input image
        width (int, optional): Target width in pixels
        height (int, optional): Target height in pixels  
        inter (int): OpenCV interpolation method (default: cv2.INTER_AREA)
    
    Returns:
        np.ndarray: Resized image
        
    Note:
        If both width and height are None, returns original image.
        If only width is provided, height is calculated to maintain aspect ratio.
        If only height is provided, width is calculated to maintain aspect ratio.
    """

Usage Example:

import cv2
import imutils

image = cv2.imread("example.jpg")

# Resize to width of 300 pixels (height calculated automatically)
resized = imutils.resize(image, width=300)

# Resize to height of 200 pixels (width calculated automatically)  
resized = imutils.resize(image, height=200)

# Use different interpolation
resized = imutils.resize(image, width=400, inter=cv2.INTER_CUBIC)

Image Rotation

Rotates images around a specified center point with optional scaling. Provides both standard rotation and boundary-adjusted rotation.

def rotate(image, angle, center=None, scale=1.0):
    """
    Rotate image around center point.
    
    Args:
        image (np.ndarray): Input image
        angle (float): Rotation angle in degrees (positive = counterclockwise)
        center (tuple, optional): (x, y) rotation center (default: image center)
        scale (float): Scaling factor (default: 1.0)
    
    Returns:
        np.ndarray: Rotated image (same dimensions as input)
    """

def rotate_bound(image, angle):
    """
    Rotate image with automatic boundary adjustment to prevent clipping.
    
    Args:
        image (np.ndarray): Input image
        angle (float): Rotation angle in degrees
    
    Returns:
        np.ndarray: Rotated image with adjusted dimensions
    """

Usage Example:

import cv2
import imutils

image = cv2.imread("example.jpg")

# Standard rotation (may clip corners)
rotated = imutils.rotate(image, 45)

# Rotation with custom center and scaling
center = (image.shape[1] // 4, image.shape[0] // 4)
rotated = imutils.rotate(image, 30, center=center, scale=0.8)

# Rotation with boundary adjustment (no clipping)
rotated_bound = imutils.rotate_bound(image, 45)

Image Translation

Translates (shifts) images by specified pixel offsets.

def translate(image, x, y):
    """
    Translate image by x, y pixels.
    
    Args:
        image (np.ndarray): Input image
        x (int): Horizontal translation (positive = right)
        y (int): Vertical translation (positive = down)
    
    Returns:
        np.ndarray: Translated image
    """

Usage Example:

import cv2
import imutils

image = cv2.imread("example.jpg")

# Shift image 25 pixels right and 75 pixels up
translated = imutils.translate(image, 25, -75)

Automatic Edge Detection

Performs automatic Canny edge detection using median-based threshold calculation.

def auto_canny(image, sigma=0.33):
    """
    Automatic Canny edge detection using median-based thresholds.
    
    Args:
        image (np.ndarray): Grayscale input image
        sigma (float): Threshold sensitivity factor (default: 0.33)
    
    Returns:
        np.ndarray: Binary edge image
        
    Note:
        Automatically calculates lower and upper thresholds based on image median.
        Lower threshold = max(0, (1.0 - sigma) * median)
        Upper threshold = min(255, (1.0 + sigma) * median)
    """

Usage Example:

import cv2
import imutils

image = cv2.imread("example.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Automatic edge detection
edges = imutils.auto_canny(gray)

# More sensitive edge detection
edges_sensitive = imutils.auto_canny(gray, sigma=0.2)

# Less sensitive edge detection  
edges_coarse = imutils.auto_canny(gray, sigma=0.5)

Image Skeletonization

Performs morphological skeletonization on binary images.

def skeletonize(image, size, structuring=cv2.MORPH_RECT):
    """
    Skeletonize binary image using morphological operations.
    
    Args:
        image (np.ndarray): Binary input image
        size (tuple): (width, height) of structuring element
        structuring (int): OpenCV morphological shape (default: cv2.MORPH_RECT)
    
    Returns:
        np.ndarray: Skeletonized binary image
    """

Usage Example:

import cv2
import imutils

# Load and binarize image
image = cv2.imread("example.jpg", cv2.IMREAD_GRAYSCALE)
_, binary = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY)

# Skeletonize with rectangular structuring element
skeleton = imutils.skeletonize(binary, (3, 3))

# Skeletonize with elliptical structuring element
skeleton_ellipse = imutils.skeletonize(binary, (5, 5), cv2.MORPH_ELLIPSE)

Color Space Conversion

Converts images between OpenCV (BGR) and Matplotlib (RGB) color formats.

def opencv2matplotlib(image):
    """
    Convert OpenCV BGR image to Matplotlib RGB format.
    
    Args:
        image (np.ndarray): BGR image from OpenCV
    
    Returns:
        np.ndarray: RGB image for Matplotlib display
    """

Usage Example:

import cv2
import imutils
import matplotlib.pyplot as plt

image = cv2.imread("example.jpg")

# Convert for matplotlib display
rgb_image = imutils.opencv2matplotlib(image)

plt.figure(figsize=(10, 6))
plt.imshow(rgb_image)
plt.axis('off')
plt.show()

URL Image Loading

Downloads and loads images directly from URLs.

def url_to_image(url, readFlag=cv2.IMREAD_COLOR):
    """
    Download and load image from URL.
    
    Args:
        url (str): Image URL
        readFlag (int): OpenCV read flag (default: cv2.IMREAD_COLOR)
    
    Returns:
        np.ndarray: Loaded image
    """

Usage Example:

import imutils

# Download and load color image
url = "https://example.com/image.jpg"
image = imutils.url_to_image(url)

# Download as grayscale
gray_image = imutils.url_to_image(url, cv2.IMREAD_GRAYSCALE)

Brightness and Contrast Adjustment

Adjusts image brightness and contrast using OpenCV's addWeighted function.

def adjust_brightness_contrast(image, brightness=0., contrast=0.):
    """
    Adjust image brightness and contrast.
    
    Args:
        image (np.ndarray): Input image
        brightness (float): Brightness adjustment (0 = no change)
        contrast (float): Contrast adjustment (0 = no change)
    
    Returns:
        np.ndarray: Adjusted image
    """

Usage Example:

import cv2
import imutils

image = cv2.imread("example.jpg")

# Increase brightness by 20 and contrast by 10%
bright = imutils.adjust_brightness_contrast(image, brightness=20, contrast=10)

# Decrease brightness and increase contrast
adjusted = imutils.adjust_brightness_contrast(image, brightness=-15, contrast=25)

Image Montage Creation

Creates image montages (grids) from lists of images.

def build_montages(image_list, image_shape, montage_shape):
    """
    Create image montages from list of images.
    
    Args:
        image_list (list): List of input images (numpy arrays)
        image_shape (tuple): (width, height) for individual images in montage
        montage_shape (tuple): (columns, rows) of montage grid
    
    Returns:
        list: List of montage images (numpy arrays)
        
    Note:
        Each montage is filled left-to-right, top-to-bottom.
        Incomplete montages are filled with black pixels.
        New montages are created when current one is full.
    """

Usage Example:

import cv2
import imutils

# Load multiple images
images = [cv2.imread(f"image_{i}.jpg") for i in range(25)]

# Create 5x5 montages with 256x256 pixel images
montages = imutils.build_montages(images, (256, 256), (5, 5))

# Display montages
for i, montage in enumerate(montages):
    cv2.imshow(f'Montage {i}', montage)
    cv2.waitKey(0)

cv2.destroyAllWindows()

OpenCV Version Compatibility

Utility functions for checking OpenCV version and handling cross-version compatibility.

def is_cv2(or_better=False):
    """
    Check if OpenCV version is 2.x.
    
    Args:
        or_better (bool): If True, check for version 2.x or higher
    
    Returns:
        bool: True if version matches criteria
    """

def is_cv3(or_better=False):
    """
    Check if OpenCV version is 3.x.
    
    Args:
        or_better (bool): If True, check for version 3.x or higher
    
    Returns:
        bool: True if version matches criteria
    """

def is_cv4(or_better=False):
    """
    Check if OpenCV version is 4.x.
    
    Args:
        or_better (bool): If True, check for version 4.x or higher
    
    Returns:
        bool: True if version matches criteria
    """

def get_opencv_major_version(lib=None):
    """
    Get the major version number of OpenCV.
    
    Args:
        lib (module, optional): OpenCV module (default: imports cv2)
    
    Returns:
        int: Major version number (e.g., 3, 4)
    """

def check_opencv_version(major, lib=None):
    """
    Check if OpenCV version matches major version (DEPRECATED).
    
    Args:
        major (str): Major version string to check (e.g., "3", "4")
        lib (module, optional): OpenCV module (default: imports cv2)
    
    Returns:
        bool: True if version matches
        
    Warning:
        This function is deprecated and may be removed in future releases.
        Use get_opencv_major_version() and is_cv* functions instead.
    """

def grab_contours(cnts):
    """
    Extract contours from cv2.findContours result (cross-version compatibility).
    
    Args:
        cnts (tuple): Result tuple from cv2.findContours
    
    Returns:
        list: Contours array
        
    Note:
        Handles differences in cv2.findContours return format across OpenCV versions.
        OpenCV 2.4 and 4.x return (contours, hierarchy).
        OpenCV 3.x returns (image, contours, hierarchy).
    """

Usage Example:

import cv2
import imutils

# Get specific version number
major_version = imutils.get_opencv_major_version()
print(f"OpenCV major version: {major_version}")

# Version checking (multiple methods)
if imutils.is_cv4():
    print("Using OpenCV 4.x")
elif imutils.is_cv3():
    print("Using OpenCV 3.x")
else:
    print("Using older OpenCV version")

# Deprecated version checking (still works but shows warning)
if imutils.check_opencv_version("4"):
    print("OpenCV 4.x detected via deprecated method")

# Cross-version contour finding
image = cv2.imread("example.jpg", cv2.IMREAD_GRAYSCALE)
cnts = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)  # Works across all OpenCV versions

print(f"Found {len(cnts)} contours")

Function Discovery

Utility for finding OpenCV functions by name pattern.

def find_function(name, pretty_print=True, module=None):
    """
    Find OpenCV functions matching name pattern.
    
    Args:
        name (str): Function name pattern to search for
        pretty_print (bool): If True, print results; if False, return list
        module: OpenCV module to search (default: cv2)
    
    Returns:
        list or None: List of matching function names if pretty_print=False
    """

Usage Example:

import imutils

# Find all functions containing "threshold"
imutils.find_function("threshold")

# Get list of matching functions
functions = imutils.find_function("blur", pretty_print=False)
print(f"Found {len(functions)} blur functions")

Install with Tessl CLI

npx tessl i tessl/pypi-imutils

docs

core-processing.md

face-analysis.md

feature-detection.md

index.md

utilities.md

video-processing.md

tile.json