Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from flask import Flask, jsonify, request, send_file
|
| 2 |
+
from flask_cors import CORS
|
| 3 |
+
from rembg import remove
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import io
|
| 6 |
+
|
| 7 |
+
app = Flask(__name__)
|
| 8 |
+
CORS(app) # Enable CORS for all routes
|
| 9 |
+
|
| 10 |
+
@app.route('/remove_background', methods=['POST'])
|
| 11 |
+
def remove_background():
|
| 12 |
+
if 'image' not in request.files:
|
| 13 |
+
return jsonify({"error": "No image provided"}), 400
|
| 14 |
+
|
| 15 |
+
input_image = request.files['image'].read() # Read the image file
|
| 16 |
+
|
| 17 |
+
# Apply background removal using rembg
|
| 18 |
+
output_bytes = remove(input_image)
|
| 19 |
+
|
| 20 |
+
# Convert the output bytes back into a PIL image
|
| 21 |
+
output_image = Image.open(io.BytesIO(output_bytes))
|
| 22 |
+
|
| 23 |
+
# Save the processed image to a BytesIO object
|
| 24 |
+
img_byte_arr = io.BytesIO()
|
| 25 |
+
output_image.save(img_byte_arr, format='PNG')
|
| 26 |
+
img_byte_arr.seek(0)
|
| 27 |
+
|
| 28 |
+
# Return the image as a response
|
| 29 |
+
return send_file(img_byte_arr, mimetype='image/png')
|
| 30 |
+
|
| 31 |
+
if __name__ == "__main__":
|
| 32 |
+
app.run(host='0.0.0.0', port=7860)
|