DEV Community

Cover image for Auto-Crop Your Screenshots Like Magic with Python
Vihanga Anuththara
Vihanga Anuththara

Posted on

Auto-Crop Your Screenshots Like Magic with Python

Here's a simple Python script I built that crops your screenshots to the real photo — automatically! (built with vibe coding)


🔧 What I Built
A Python script that auto-crops mobile screenshots to show only the actual photo — no app frames, no clutter. Just clean photos!

💡 Why?
Sometimes I screenshot photos from apps like Instagram, and I just want the image — not the app UI or background. Manually cropping each one is a pain. So I automated it. 😎


Here's the source code for the script mentioned above:

import cv2
import numpy as np
import os

input_folder = 'screenshots'
output_folder = 'cropped'

os.makedirs(output_folder, exist_ok=True)

for file in os.listdir(input_folder):
    if file.lower().endswith(('.png', '.jpg', '.jpeg')):
        path = os.path.join(input_folder, file)
        img = cv2.imread(path)
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

        # Threshold to isolate the content
        _, thresh = cv2.threshold(gray, 245, 255, cv2.THRESH_BINARY_INV)

        # Find contours
        contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        if contours:
            # Get bounding box of largest contour
            c = max(contours, key=cv2.contourArea)
            x, y, w, h = cv2.boundingRect(c)

            cropped = img[y:y+h, x:x+w]
            output_path = os.path.join(output_folder, file)
            cv2.imwrite(output_path, cropped)
            print(f'Cropped: {file}')
        else:
            print(f'No content found in: {file}')

Enter fullscreen mode Exit fullscreen mode

🔍 What It Does

  • Scans your "screenshots" folder for images
  • Detects the real content area
  • Crops out everything else
  • Saves cropped versions to a "cropped" folder
  • All automatic 🚀

🧠 Tech Used

  • cv2 (OpenCV)
  • numpy

You just need:

  • A folder named screenshots
  • The script will take care of the rest — creating a cropped folder and saving your results there.

🧪 How to Use

  1. Place your screenshots inside a folder named screenshots
  2. Run the script
  3. Open the cropped folder and enjoy your clean images!

Bonus Tip: You can customize the crop detection based on your device screen or app layout.

Top comments (0)