Skip to main content
Change of provenance

The repository or configuration that created this release differ from a previous release. View details.

rectcropper

Find objects on simple backgrounds. Save separate crops or transparent cutouts.

PyPI Tests Python License: MIT

A small Python library and command line tool built on NumPy, Pillow, and SciPy. No model downloads or training. Best for product images, simple graphics, and objects surrounded by relatively uniform background colors.

Real examples · Get started · Output shapes · Detection controls · Full reference

Version 1.3.0 includes transparent object/circle/ellipse output, an optimized exact-output pipeline, and bounded batch processing. Install or upgrade with pip to use all features below.

Real-world examples

Extract a book cover from a store listing, a photo from a news page, or a product image from a catalog. These are the original examples from the project's 2021 README; the screenshots show the historical results.

Book covers from a bookstore

Original bookstore example showing book covers extracted from a listing

Photos from a news page

Original newspaper example showing photographs extracted from a page
More original examples: marketplace, website, and image search

Marketplace products

Original marketplace example showing rectangular product crops

Website images

Original website image extraction example

Image search results

Original image search example with multiple extracted pictures

Get started

Python 3.9+ is required. Dependencies are installed automatically.

python -m pip install --upgrade rectcropper

Crop from the command line:

rectcropper input.png -o crops --min-width 40 --min-height 40

Or use one Python call. The result is a list of independent Pillow images:

from rectcropper import crop_image

images = crop_image('input.png', min_crop_width=40, min_crop_height=40)

Add output_dir='crops' to save files too. Output directories are created automatically; the default names are input_1.png, input_2.png, and so on. Matching filenames are overwritten; unrelated or leftover files are not removed.

The helper and CLI use RGB border detection by default. Minimum width and height default to 100 × 100; lower them for smaller objects, as shown above.

How cropping works

One input image becomes three independent object cutouts

The diagrams below use reproducible synthetic inputs to make each option's effect clear. Real photographs still need a background that the color heuristic can separate from the object.

Choose an output shape

Actual inputs and rectangle, object outline, circle, and ellipse outputs

Checkerboard means transparency. Thin outlines mark each image's canvas. The ring example shows why a shape mask is useful: object removes the white hole and excludes the separate purple object inside the ring's bounding box.

Output What it does Python option / CLI flag
Rectangle Keeps the original contents of each bounding box Default
Object outline Keeps only that detected component; background and holes become transparent output_shape='object' / --shape object
Circle Applies a centered circle to the crop output_shape='circle' / --shape circle
Ellipse Applies an ellipse that fills the crop box output_shape='ellipse' / --shape ellipse

Transparent output is available in version 1.3.0 and newer:

images = crop_image(
    'input.png',
    output_shape='object',
    output_dir='cutouts',
    min_crop_width=40,
    min_crop_height=40,
    padding=8,
)
rectcropper input.png -o cutouts --shape object --min-width 40 --min-height 40

All output files still have rectangular canvases. Circle/ellipse masks cut away parts outside their geometry; they do not remove background inside it. Use PNG to retain transparency. JPEG flattens it onto white. Masks have hard pixel edges, and preserve existing source alpha inside the selected region.

Control detection and spacing

RGB background detection, foreground area filtering, and transparent padding compared using actual outputs

Goal Option Effect
Distinguish different colors with equal brightness background_mode='border' Estimates RGB background colors from the image perimeter
Use a known background background_colors=[(255, 255, 255)] Overrides automatic background selection
Ignore tiny specks min_area=100 Rejects components with fewer than 100 actual foreground pixels
Add space around a crop padding=20 Adds up to 20 pixels per side, clipped to the input boundary
Group diagonal neighbors connectivity=8 Joins diagonal pixels; the default 4 joins edge neighbors only
Adjust background tolerance pixel_sensitivity=5 Sets the allowed color difference; 0 means exact matching

Width, height, and area filters apply before padding. Object-mode padding is transparent; default rectangle padding keeps the original image pixels. Padded boxes can overlap and are not merged. Crops are fitted independently in the figures; the padding comparison uses the same pixel scale and shows canvas borders.

Process many files

crop_images() saves files and yields small metadata results instead of returning all images in memory. Serial execution is the default; opt into processes for larger workloads:

from pathlib import Path
from rectcropper import crop_images

if __name__ == '__main__':
    for result in crop_images(
        Path('inputs').glob('*.png'),
        output_dir='crops',
        workers=2,
        max_pending=4,
        min_crop_width=40,
        min_crop_height=40,
    ):
        print(result.input_path, result.crop_points, result.output_paths)

Results follow input order. Each input gets an indexed subdirectory, such as crops/000000-photo/photo_1.png, so identical stems within the batch do not collide. Only max_pending tasks are submitted at once. The __main__ guard is required for spawn-based process workers in scripts; serial mode (workers=1) avoids that startup overhead. Parallel execution is not a speed guarantee for small batches. See the batch reference for errors, cleanup, and overwrite behavior. This API is available in version 1.3.0 and newer.

Need coordinates or masks?

Use the class directly for repeated calls, metadata, or processing one crop at a time. Its default detection mode is legacy; choose border to match the helper.

from rectcropper import RectangleCropper

cropper = RectangleCropper()
cropper.open('input.png')
cropper.crop(background_mode='border', output_shape='object')

for box, mask, image in zip(cropper.get_crop_points(),
                            cropper.iter_masks(), cropper.iter_crops()):
    print(box, mask.size, image.mode)

Boxes use (left, top, right, bottom) with exclusive right/bottom edges. Masks are independent Pillow L images containing 0/255 selection values; cropped RGBA images also preserve source alpha. EXIF orientation is applied before detection. Object mode retains an image-sized component label array until the next open/crop.

Performance and limits

Version 1.3.0 further reduces temporary arrays and discarded-component work. In follow-up fixtures it was 1.5–2.0× faster with retained objects and up to 4.35× faster when all specks were rejected; traced crop allocations fell about 32% for the border-mode two-object fixture. See the measured follow-up and reproduction.

The vectorized engine measured 111–137× faster than the corrected earlier Python traversal on two synthetic fixtures. These are crop-only medians of three runs on Python 3.10/macOS, with matching boxes; import/open/save times are excluded. They are not speed guarantees for other inputs. Benchmark details and reproduction.

This is a background-color heuristic, not general-purpose segmentation or perspective correction. Textured backgrounds, shadows, gradients, and objects covering the perimeter can defeat automatic detection. Transparency is preserved in output but is not used as a segmentation signal. Touching objects may form one component, and geometric masks can cut off parts of an object.

More documentation

The figures are generated from actual API outputs, including assertions for object counts and crop dimensions. Regenerate them with:

python docs/generate_visuals.py

MIT license.

Metadata

Release files for rectcropper 1.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Change of provenance

The repository or configuration that created these release files differ from that of a previous release.

We recommend inspecting the repository and configuration before proceeding. View details.

Source distribution (sdist)

Source distribution for rectcropper 1.3.0
File Size Uploaded Provenance Actions
rectcropper-1.3.0.tar.gz 150.0 kB With provenance Details for rectcropper-1.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for rectcropper 1.3.0
File Interpreter ABI Platform Actions
rectcropper-1.3.0-py3-none-any.whl Python 3 none any Details for rectcropper-1.3.0-py3-none-any.whl

Total release size: 166.1 kB

Release files / rectcropper-1.3.0.tar.gz

Change of provenance

This file belongs to a release with changed provenance: the repository or configuration that created the release files differ from that of a previous release.

We recommend inspecting the repository and configuration before proceeding. View details.

Download URL rectcropper-1.3.0.tar.gz
Size 150.0 kB
Tags Source
SHA-256 checksum
How to use checksums
5ba62c9cfece24051e0bc2776acefec05d47484ef1992eda12b93a947aec3a1b
BLAKE2b-256 checksum
How to use checksums
04bd87aa986df67bbac8d88e5ee38128325704972d997f94f8d03b07dbe3931f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 1, 2026.

Transparency log

Release files / rectcropper-1.3.0-py3-none-any.whl

Change of provenance

This file belongs to a release with changed provenance: the repository or configuration that created the release files differ from that of a previous release.

We recommend inspecting the repository and configuration before proceeding. View details.

Download URL rectcropper-1.3.0-py3-none-any.whl
Size 16.1 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c71fb3c8eaeb38718dcd66940fc82c3a4f924cef7b2fe7431bab70eac3802555
BLAKE2b-256 checksum
How to use checksums
a9fa4195e5e2b2ce8b5bc1b01e73bf0f861407cf79abf0bf5ef6920d76e0b1db
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 1, 2026.

Transparency log

Security for rectcropper 1.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Change of provenance

The repository and configuration that created this release differ from a previous release.

While this could reflect a routine change by the project maintainers, it may also indicate that the release files have been compromised.

Select from 2 files

Attestation for rectcropper-1.3.0.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 1, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page