Skip to main content

Smart Image Cropper

PyPI version Python Support License: MIT

An intelligent image cropping library that automatically detects objects in images and creates optimized crops or collages. The library uses AI-powered bounding box detection to identify the most important regions in your images and intelligently crops them to standard aspect ratios.

Features

  • 🎯 Smart Object Detection: Automatically detects important objects in images using AI
  • 🖼️ Intelligent Cropping: Crops images to optimal aspect ratios (4:5, 3:4, 1:1, 4:3)
  • 🎨 Automatic Collages: Creates beautiful collages when multiple objects are detected
  • 📐 Aspect Ratio Optimization: Automatically expands crops to reach target aspect ratios
  • 🔧 Flexible Input: Supports URLs, bytes, and PIL Images as input
  • ⚡ Fast Processing: Efficient image processing with OpenCV
  • 🐍 Pure Python: Easy to integrate into any Python project
  • 🔄 Multiple request modes: Polling, webhook, single

Installation

pip install smart-image-cropper

Quick Start

from smart_image_cropper import SmartImageCropper

# Initialize the cropper with your API credentials
cropper = SmartImageCropper(
    api_url="your-api-endpoint",
    api_key="your-api-key"
)

Getting Bounding Boxes

The library supports three modes for getting bounding boxes:

  1. Polling (default mode):
# Automatically waits for job completion
bboxes = cropper.get_bounding_boxes(image_input, mode="polling")
  1. Webhook:
# Sends request and returns job ID
job_id = cropper.get_bounding_boxes(
    image_input,
    mode="webhook",
    webhook_url="https://your-webhook.com"
)

# The webhook will receive results when the job is completed
# The webhook payload will contain bounding boxes in the format:
# {
#     "delayTime": 1000,
#     "executionTime": 1000,
#     "input": {
#         "image": "image_bytes",
#     },
#     "id": "job_123",
#      "input": {
#         "image": "image_bytes",
#     },
#     "status": "COMPLETED",
#     "output": [
#         {"x1": 0, "y1": 0, "x2": 100, "y2": 100},
#         ...
#     ],
#     "webhook": "https://your-webhook.com"
# }
  1. Single Request:
# Only sends the request without waiting for results
cropper.get_bounding_boxes(image_input, mode="single")

Creating a Collage

# After getting bounding boxes
collage = cropper.create_collage(image_input, bboxes)

Examples

Complete Example with Polling

from smart_image_cropper import SmartImageCropper
from PIL import Image

# Initialize the cropper
cropper = SmartImageCropper("https://api.example.com/detect", "your_api_key")

# Load the image
image = Image.open("example.jpg")

# Get bounding boxes (polling mode)
bboxes = cropper.get_bounding_boxes(image)

# Create the collage
result = cropper.create_collage(image, bboxes)

# Save the result
with open("result.jpg", "wb") as f:
    f.write(result)

Webhook Example with Flask

from smart_image_cropper import SmartImageCropper, BoundingBox
from flask import Flask, request

app = Flask(__name__)
cropper = SmartImageCropper("https://api.example.com/detect", "your_api_key")

@app.route("/process", methods=["POST"])
def process_image():
    image = request.files["image"]
    job_id = cropper.get_bounding_boxes(
        image.read(),
        mode="webhook",
        webhook_url="https://your-server.com/webhook"
    )
    return {"job_id": job_id}

@app.route('/webhook', methods=['POST'])
def webhook():
    data = request.json
    job_id = data.get('id')
    if job_id and data.get('status') == 'COMPLETED':
        # Parse bounding boxes from the webhook data
        bboxes = [
            BoundingBox(
                x1=bbox['x1'],
                y1=bbox['y1'],
                x2=bbox['x2'],
                y2=bbox['y2']
            )
            for bbox in data.get('output', [])
        ]
        webhook_results[job_id] = bboxes
    return jsonify({'status': 'ok'})

Notes

  • Polling mode is the simplest to use but may block execution for a while
  • Webhook mode is ideal for asynchronous applications or web servers
  • Single mode is useful when you just want to send the request without waiting for results

How It Works

  1. The library sends the image to an AI-powered API for object detection
  2. The API returns bounding boxes for detected objects
  3. The library selects the best bounding boxes based on size and position
  4. The image is cropped or a collage is created based on the selected boxes
  5. The result is returned as image bytes

Installation

pip install smart-image-cropper

License

MIT

Dependencies

  • OpenCV (opencv-python>=4.5.0) - Image processing
  • NumPy (numpy>=1.20.0) - Numerical operations
  • Pillow (Pillow>=8.0.0) - PIL Image support
  • Requests (requests>=2.25.0) - HTTP API calls

Development

Setting Up Development Environment

# Clone the repository
git clone https://github.com/yourusername/smart-image-cropper.git
cd smart-image-cropper

# Install in development mode
pip install -e ".[dev]"

# Run tests
pytest

# Format code
black .

# Type checking
mypy smart_image_cropper/

Running Tests

pytest tests/ -v --cov=smart_image_cropper

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

License

This project is licensed under the MIT License - see the LICENSE file for details.

Changelog

v1.0.0

  • Initial release
  • Support for URL, bytes, and PIL Image inputs
  • Automatic object detection and smart cropping
  • Collage creation for multiple objects
  • Aspect ratio optimization

Support

If you encounter any issues or have questions, please file an issue on the GitHub issue tracker.

Acknowledgments

  • OpenCV community for excellent image processing tools
  • PIL/Pillow developers for image handling capabilities
  • The Python packaging community for excellent tools and documentation

Metadata

Release files for smart-image-cropper 1.4.1

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

Source distribution (sdist)

Source distribution for smart-image-cropper 1.4.1
File Size Uploaded Provenance Actions
smart_image_cropper-1.4.1.tar.gz 30.4 kB Without provenance Details for smart_image_cropper-1.4.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for smart-image-cropper 1.4.1
File Interpreter ABI Platform Actions
smart_image_cropper-1.4.1-py3-none-any.whl Python 3 none any Details for smart_image_cropper-1.4.1-py3-none-any.whl

Total release size: 47.7 kB

Release files / smart_image_cropper-1.4.1.tar.gz

Download URL smart_image_cropper-1.4.1.tar.gz
Size 30.4 kB
Tags Source
SHA-256 checksum
How to use checksums
0937e1b7c621c055cd2f02582e3fad55ca004f511236f11ada6568dce80897cf
BLAKE2b-256 checksum
How to use checksums
0cbb821aedcfb7aa46e331da3b88724a431584cb85711463b1c88e16a9693b4c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.7

Release files / smart_image_cropper-1.4.1-py3-none-any.whl

Download URL smart_image_cropper-1.4.1-py3-none-any.whl
Size 17.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d020bf715ff7e1db13a9e5f4c9d7ee828f499c43f0782e642bc2d541d5d55618
BLAKE2b-256 checksum
How to use checksums
eedd7baeeafeb35a37169603f0fe4d3a6b6d513718080f65b8676a2a0259e3a1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.7

Security for smart-image-cropper 1.4.1

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.

No provenance found

None of the files in this release were uploaded with provenance metadata.

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