Skip to content
Search

OpenCV:Example:CropCenter

lastmod 2022-07-11created 2022-07-114 edits

Crop around the center

Python

Works with both numpy and PIL formats

import numpy as np
from PIL.Image import Image
from typing import Union


def crop_center(image: Union[np.ndarray, Image]) -> Union[np.ndarray, Image]:
    if isinstance(image, np.ndarray):
        y, x, c = image.shape
        m = min(x, y)
        x1 = x // 2 - (m // 2)
        y1 = y // 2 - (m // 2)
        x2 = x1 + m
        y2 = y1 + m
        return image[y1:y2, x1:x2]
    elif isinstance(image, Image):
        x, y = image.width, image.height
        m = min(x, y)
        x1 = x // 2 - (m // 2)
        y1 = y // 2 - (m // 2)
        x2 = x1 + m
        y2 = y1 + m
        return image.crop((x1, y1, x2, y2))
    else:
        raise TypeError(f"Unsupported image type: {type(image).__name__}")

See also

Favorite site

author Zer0 sitemap