You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Flask部署含OpenCV与TensorFlow的Python 3.6.3项目至Web服务器

Got it, let's walk through how to get your Python 3.6.3 project (with those specific OpenCV and TensorFlow versions) up and running as a Flask web app. Here's a step-by-step breakdown tailored to your setup:

Deploy Your CV/TensorFlow Project as a Flask Web Service

1. Match Your Server Environment to Local

First, you need to replicate your local dependency setup on the web server to avoid version conflicts.

  • Install Python 3.6.3 on the server if it's not already present.
  • Create and activate a virtual environment to isolate dependencies:
    # Create virtual environment
    python3.6 -m venv flask_project_env
    
    # Activate on Linux/macOS
    source flask_project_env/bin/activate
    
    # Activate on Windows
    flask_project_env\Scripts\activate
    
  • Install your exact required packages plus Flask:
    pip install opencv-python==3.4.0.12 tf-nightly==1.8.0.dev20180329 flask
    

2. Refine Flask and Main Script Integration

Your initial idea of calling main.py from Flask is solid, but we need to adjust it to return proper HTTP responses (since web apps can't just run functions silently). Here are two common scenarios:

Basic Text/Result Response

Rename your Flask.py to app.py (standard Flask naming) and update it to return a usable response:

from flask import Flask, jsonify
import main

app = Flask(__name__)

@app.route('/')
def run_project():
    # Call your main function and capture its output
    project_output = main.some_func()
    # Return a JSON response (easy to consume for frontends)
    return jsonify({"status": "success", "output": project_output})

if __name__ == '__main__':
    # Bind to all server interfaces so it's accessible externally
    app.run(host='0.0.0.0', port=5000, debug=False)

Image Processing Workflow (Common for CV Projects)

If your project processes images (e.g., object detection, image classification), add a route to handle file uploads:

from flask import Flask, request, jsonify
import main
import cv2
import numpy as np

app = Flask(__name__)

@app.route('/process-image', methods=['POST'])
def process_uploaded_image():
    if 'image' not in request.files:
        return jsonify({"error": "No image file provided"}), 400
    
    img_file = request.files['image']
    # Convert uploaded file to OpenCV-readable format
    img = cv2.imdecode(np.frombuffer(img_file.read(), np.uint8), cv2.IMREAD_COLOR)
    # Call your main processing function
    result = main.process_image(img)
    return jsonify({"processing_result": result})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

Update main.py to support this workflow (and initialize models once, not per request, to save resources):

# main.py
import cv2
import tensorflow as tf

# Initialize your TensorFlow model once at startup (critical for performance)
model = tf.keras.models.load_model('your_trained_model.h5')

def some_func():
    # Your existing core logic here
    return "Project is running on Flask!"

def process_image(img):
    # Example preprocessing + prediction
    resized_img = cv2.resize(img, (224, 224))
    img_array = np.expand_dims(resized_img, axis=0)
    prediction = model.predict(img_array)
    return prediction.tolist()

3. Production-Ready Deployment

For real-world use, don't rely on app.run()—use a production WSGI server like Gunicorn:

  • Install Gunicorn:
    pip install gunicorn
    
  • Start the server (adjust worker count based on your server's CPU cores):
    gunicorn --workers=4 --bind=0.0.0.0:5000 app:app
    
  • Optional: Add Nginx as a reverse proxy to handle static files, SSL, and traffic routing (but this is extra for scaling).

4. Test Your Deployment

Once the server is running, test it with simple commands:

  • Test the base route:
    curl http://your-server-ip:5000/
    
  • Test image processing (if applicable):
    curl -X POST -F "image=@test_image.jpg" http://your-server-ip:5000/process-image
    

内容的提问来源于stack exchange,提问作者Aadit

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 03:30:01