38180-vm/core/utils.py
2026-02-04 20:27:35 +00:00

49 lines
1.8 KiB
Python

from PIL import Image, ImageOps, ImageChops
import os
def process_clothing_image(image_path):
"""
Processes a clothing image:
1. Removes background (simplified version without ML if not available).
2. Crops to the garment boundaries.
3. Converts background to white.
"""
try:
img = Image.open(image_path).convert("RGBA")
# 1. Background removal / White background conversion
# Since we don't have rembg, we'll try a simple approach:
# If the background is already somewhat light, we can treat it as background.
# This is a fallback for true ML-based background removal.
datas = img.getdata()
new_data = []
# Simple heuristic: pixels that are very bright or very dark (if it's a studio shot)
# For more precision, we'd need a real segmentation model.
for item in datas:
# If the pixel is very white, make it transparent for cropping logic
if item[0] > 240 and item[1] > 240 and item[2] > 240:
new_data.append((255, 255, 255, 0))
else:
new_data.append(item)
img.putdata(new_data)
# 2. Automatic Cropping
# Get the bounding box of non-transparent areas
bbox = img.getbbox()
if bbox:
img = img.crop(bbox)
# 3. Add White Background
background = Image.new("RGB", img.size, (255, 255, 255))
background.paste(img, mask=img.split()[3]) # 3 is the alpha channel
# Save back to the same path or a new one
background.save(image_path, "JPEG", quality=95)
return True
except Exception as e:
print(f"Error processing image {image_path}: {e}")
return False