import os from flask import Flask, render_template, request, jsonify import cv2 import numpy as np from werkzeug.utils import secure_filename import base64 app = Flask(__name__) app.config['UPLOAD_FOLDER'] = 'static/uploaded' app.config['ALLOWED_EXTENSIONS'] = {'png', 'jpg', 'jpeg'} def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS'] def adjust_curves(image, r_curve, g_curve, b_curve, y_curve): # 各チャンネルを分離 b, g, r = cv2.split(image) # 明るさチャンネルを計算 y = (0.299 * r + 0.587 * g + 0.114 * b).astype(np.uint8) # 各チャンネルにカーブを適用 b = apply_lut(b, b_curve) g = apply_lut(g, g_curve) r = apply_lut(r, r_curve) y_adjusted = apply_lut(y, y_curve) # 明るさ調整をRGBに反映 ratio = np.where(y == 0, 0, y_adjusted / y).clip(0, 3) r = (r * ratio).clip(0, 255).astype(np.uint8) g = (g * ratio).clip(0, 255).astype(np.uint8) b = (b * ratio).clip(0, 255).astype(np.uint8) return cv2.merge((b, g, r)) def apply_lut(channel, curve_points): x = np.array([0, 64, 128, 192, 255]) y = np.array(curve_points) lut = np.interp(np.arange(256), x, y).astype(np.uint8) return cv2.LUT(channel, lut) @app.route('/') def index(): default_curve = [0, 64, 128, 192, 255] return render_template('index.html', r_curve=default_curve, g_curve=default_curve, b_curve=default_curve, y_curve=default_curve) @app.route('/api/process_image', methods=['POST']) def process_image(): if request.method == 'OPTIONS': return _build_cors_preflight_response() elif request.method == 'POST': # リクエストデータを取得 data = request.json file_data = data['image'].split(',')[1] img_bytes = base64.b64decode(file_data) # バイトデータから画像を読み込み nparr = np.frombuffer(img_bytes, np.uint8) img = cv2.imdecode(nparr, cv2.IMREAD_COLOR) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # カーブパラメータを取得 r_curve = [int(x) for x in data['r_curve']] g_curve = [int(x) for x in data['g_curve']] b_curve = [int(x) for x in data['b_curve']] y_curve = [int(x) for x in data['y_curve']] # 画像処理 adjusted_img = adjust_curves(img, r_curve, g_curve, b_curve, y_curve) # 画像をJPEGにエンコード _, buffer = cv2.imencode('.jpg', cv2.cvtColor(adjusted_img, cv2.COLOR_RGB2BGR)) img_base64 = base64.b64encode(buffer).decode('utf-8') return _corsify_response(jsonify({ 'status': 'success', 'image': 'data:image/jpeg;base64,' + img_base64 })) except Exception as e: return jsonify({ 'status': 'error', 'message': str(e) }), 500 def _build_cors_preflight_response(): response = jsonify({'message': 'Preflight Request'}) response.headers.add("Access-Control-Allow-Origin", "*") response.headers.add("Access-Control-Allow-Headers", "*") response.headers.add("Access-Control-Allow-Methods", "*") return response def _corsify_response(response): response.headers.add("Access-Control-Allow-Origin", "*") return response if __name__ == '__main__': os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True) app.run(debug=True, port=7860, host="0.0.0.0")