RemBG_API / main.py
VINU NAYAK
Upload main.py
31a275e verified
Raw
History Blame
1.66 kB
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
import io
from PIL import Image
from rembg import remove
app = FastAPI(title="Background Removal API")
# Add CORS middleware to allow requests from any origin
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
def read_root():
return {"message": "Background Removal API is running. Use POST /remove-bg to remove background from an image."}
@app.post("/remove-bg")
async def remove_background(file: UploadFile = File(...)):
# Check if the file is an image
if not file.content_type.startswith("image/"):
raise HTTPException(status_code=400, detail="File must be an image")
try:
# Read the image
contents = await file.read()
input_image = Image.open(io.BytesIO(contents))
# Remove the background
output_image = remove(input_image)
# Convert to bytes
img_byte_arr = io.BytesIO()
output_image.save(img_byte_arr, format="PNG")
img_byte_arr.seek(0)
# Return the processed image
return StreamingResponse(
content=img_byte_arr,
media_type="image/png"
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error processing image: {str(e)}")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860)