Skip to main content

An intelligent image cropping library that creates smart collages

Project description

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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

smart_image_cropper-1.3.0.tar.gz (27.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

smart_image_cropper-1.3.0-py3-none-any.whl (14.7 kB view details)

Uploaded Python 3

File details

Details for the file smart_image_cropper-1.3.0.tar.gz.

File metadata

  • Download URL: smart_image_cropper-1.3.0.tar.gz
  • Upload date:
  • Size: 27.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.8.18

File hashes

Hashes for smart_image_cropper-1.3.0.tar.gz
Algorithm Hash digest
SHA256 f893ae1d9befbcc18813185d2645fd2b6ae70ed0d956dd819509545c4d7745cc
MD5 0c68dfa6cc177dfa2ca241d074b2aee9
BLAKE2b-256 00377ff952ba4712be271344f5f3856167f7fb5dab5dfd3bf45db1ba4b142468

See more details on using hashes here.

File details

Details for the file smart_image_cropper-1.3.0-py3-none-any.whl.

File metadata

File hashes

Hashes for smart_image_cropper-1.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 dc093016b01b70e109e2fab113b8e815d86ca2b5044f765f5146171c8c55d187
MD5 605e0364a987d8cef6bee2df437e9aea
BLAKE2b-256 3b4143518246983032a5e2ea8cfdaebb214ec20db8c4da5c1177bb82a83778b3

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page