Create rembg_method.py
Browse files- rembg_method.py +40 -0
rembg_method.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from PIL import Image
|
| 2 |
+
import io
|
| 3 |
+
import logging
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
|
| 6 |
+
logger = logging.getLogger(__name__)
|
| 7 |
+
|
| 8 |
+
def remove_background(image_data):
|
| 9 |
+
start_time = datetime.now()
|
| 10 |
+
logger.info(f"Removing background - {start_time}")
|
| 11 |
+
|
| 12 |
+
try:
|
| 13 |
+
# Try to import rembg
|
| 14 |
+
try:
|
| 15 |
+
from rembg import remove
|
| 16 |
+
logger.info("rembg module imported successfully")
|
| 17 |
+
except ImportError:
|
| 18 |
+
logger.error("rembg module not found!")
|
| 19 |
+
raise ImportError('rembg library not installed')
|
| 20 |
+
|
| 21 |
+
input_image = Image.open(io.BytesIO(image_data))
|
| 22 |
+
logger.info(f"Image opened. Mode: {input_image.mode}, Size: {input_image.size}")
|
| 23 |
+
|
| 24 |
+
if input_image.mode != 'RGB':
|
| 25 |
+
logger.info("Converting image to RGB...")
|
| 26 |
+
input_image = input_image.convert('RGB')
|
| 27 |
+
|
| 28 |
+
logger.info("Removing background...")
|
| 29 |
+
output_image = remove(input_image)
|
| 30 |
+
|
| 31 |
+
img_io = io.BytesIO()
|
| 32 |
+
output_image.save(img_io, 'PNG')
|
| 33 |
+
img_io.seek(0)
|
| 34 |
+
|
| 35 |
+
duration = (datetime.now() - start_time).total_seconds()
|
| 36 |
+
logger.info(f"Successfully processed. Duration: {duration} seconds")
|
| 37 |
+
return img_io
|
| 38 |
+
except Exception as e:
|
| 39 |
+
logger.error(f"Background removal error: {str(e)}", exc_info=True)
|
| 40 |
+
raise
|