#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import cv2 | |
import numpy as np | |
import sys | |
import os | |
def remove_white_borders(image_path): | |
# Read the image | |
image = cv2.imread(image_path) | |
# Convert the image to grayscale | |
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) | |
# Apply a binary threshold to get a binary image | |
_, binary = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY) | |
# Invert the binary image | |
binary = cv2.bitwise_not(binary) | |
# Find contours in the binary image | |
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) | |
# Get the bounding box of the largest contour | |
x, y, w, h = cv2.boundingRect(contours[0]) | |
# Crop the image using the bounding box | |
cropped_image = image[y:y+h, x:x+w] | |
# Create the output path with the -cropped suffix | |
base, ext = os.path.splitext(image_path) | |
output_path = f"{base}-cropped.png" | |
# Save the cropped image in lossless PNG format | |
cv2.imwrite(output_path, cropped_image) | |
print(f"Cropped image saved as {output_path}") | |
if __name__ == "__main__": | |
if len(sys.argv) != 2: | |
print("Usage: python script.py <image_path>") | |
else: | |
image_path = sys.argv[1] | |
remove_white_borders(image_path) | |