from flask import Flask, render_template, request
import cv2
import numpy as np
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/remove_background', methods=['POST'])
def remove_background():
if 'image' not in request.files:
return render_template('index.html', error='No image file selected.')
# Read the uploaded image
image = request.files['image'].read()
nparr = np.frombuffer(image, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
# Apply background removal algorithm (example: using OpenCV's grabCut)
mask = np.zeros(img.shape[:2], np.uint8)
bgd_model = np.zeros((1, 65), np.float64)
fgd_model = np.zeros((1, 65), np.float64)
rect = (1, 1, img.shape[1] - 1, img.shape[0] - 1)
cv2.grabCut(img, mask, rect, bgd_model, fgd_model, 5, cv2.GC_INIT_WITH_RECT)
mask = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')
result = img * mask[:, :, np.newaxis]
# Save the result or display it directly (depends on your implementation)
# cv2.imwrite('result.png', result)
# Render the template with the result
return render_template('index.html', result=result)
if __name__ == '__main__':
app.run()
No comments: