from flask import Flask, request, jsonify, send_file, render_template_string import os import cv2 from rembg import new_session, remove from rembg.sessions import sessions_class import base64 import uuid from flask_cors import CORS app = Flask(__name__) CORS(app) # セッションの初期化 for session in sessions_class: session.download_models() def process_image(file_path, mask, model, x, y): im = cv2.imread(file_path, cv2.IMREAD_COLOR) input_path = f"temp_input_{uuid.uuid4().hex}.png" output_path = f"temp_output_{uuid.uuid4().hex}.png" cv2.imwrite(input_path, im) with open(input_path, 'rb') as i: with open(output_path, 'wb') as o: input_data = i.read() session = new_session(model) output = remove( input_data, session=session, **{"sam_prompt": [{"type": "point", "data": [x, y], "label": 1}]}, only_mask=(mask == "Mask only") ) o.write(output) # 一時ファイルを削除 if os.path.exists(input_path): os.remove(input_path) return output_path @app.route('/api/process', methods=['POST']) def api_process(): if 'file' not in request.files: return jsonify({'error': 'No file uploaded'}), 400 file = request.files['file'] mask = request.form.get('mask', 'Default') model = request.form.get('model', 'isnet-general-use') x = request.form.get('x', None) y = request.form.get('y', None) try: x = float(x) if x is not None else None y = float(y) if y is not None else None except (TypeError, ValueError): x = None y = None # 一時ファイルに保存 temp_input = f"temp_{uuid.uuid4().hex}.png" file.save(temp_input) try: output_path = process_image(temp_input, mask, model, x, y) return send_file(output_path, mimetype='image/png') except Exception as e: return jsonify({'error': str(e)}), 500 finally: # 一時ファイルを削除 if os.path.exists(temp_input): os.remove(temp_input) HTML_TEMPLATE = """ RemBG API

RemBG API

Upload an image to process with RemBG. Select options and click "Process Image".

Input image will appear here
Output image will appear here
""" @app.route('/') def index(): return render_template_string(HTML_TEMPLATE) if __name__ == '__main__': app.run(host='0.0.0.0', port=7860)