Skip to main content
In this guide you’ll create a minimal Flask app that accepts image uploads, processes the uploaded image with OpenCV (for example, compressing JPEG quality), and returns JSON with the path to the processed file. The tutorial covers endpoint validation, saving uploads securely, controlling JPEG compression via a quality form parameter, and troubleshooting common errors when testing with Postman or curl.
A presentation slide that reads "Implementing OpenCV" on the left and a large turquoise "Demo" on a dark curved shape on the right. Copyright KodeKloud appears in the bottom-left corner.
What this tutorial covers
  • Create an upload route that accepts multipart/form-data POSTs with an image file.
  • Store the original upload in a configured upload folder.
  • Use OpenCV to compress the image by changing JPEG quality (configurable via a quality form parameter).
  • Return JSON that points to the processed image path.
Quick install
Why this approach (summary)
  • Simple, production-proximate pattern: use an application factory to create the Flask app, configure an upload folder, and import route registrations inside the app context.
  • Keep route logic concise and validate inputs early: verify file presence, filename, and the numeric quality range (0–100).
  • Use OpenCV for image decoding/encoding and to control JPEG compression via cv2.IMWRITE_JPEG_QUALITY.
Files referenced in examples Minimal routes (routes.py)
  • This file assumes it’s imported after the Flask app has been created (for example, via an application factory that imports routes inside an app context). The examples use current_app as a reference to the Flask application; make sure routes is imported while the application context is active. In many projects, using a Blueprint or importing the app instance directly is preferred.
Upload endpoint: functionality and validation
  • The /upload handler below:
    • Validates that the request contains an image file part.
    • Verifies a filename is present.
    • Ensures the configured upload folder exists and saves the original file.
    • Reads the image using OpenCV, validates successful decode, and writes a compressed JPEG with the requested quality (default is 10).
    • Returns a JSON response with the processed image path.
Application factory example (app/init.py)
  • When using an application factory set the UPLOAD_FOLDER on the app config. Import routes inside the app context so current_app is available within routes.py. Avoid calling app.run() inside modules that register routes.
Simple HTML form (templates/base.html)
  • Be sure the form uses enctype="multipart/form-data" and posts to /upload.
Testing with curl
  • Example curl command to test the /upload endpoint locally:
Expected successful JSON response
Troubleshooting common errors
This Flask development server is not intended for production. Use a production WSGI server (for example, gunicorn or uWSGI) behind a proper web server or load balancer for production deployments.
Additional tips and best practices
  • Ensure your upload folder exists and is writable by the Flask process, or create it programmatically with os.makedirs(upload_folder, exist_ok=True).
  • Always validate and sanitize filenames in production. Use werkzeug.utils.secure_filename to avoid path traversal issues and remove unsafe characters.
  • If you prefer to return the processed image bytes directly instead of a filesystem path, use Flask’s send_file() with the processed path or read the bytes and return them with the appropriate Content-Type.
  • To view detailed error pages during development, enable debug mode only for local development (for recent Flask versions set FLASK_DEBUG=1 or configure debug in your app’s config).
  • Consider storing images in a dedicated storage service (S3, GCS) for scalability rather than saving them locally on the web server for production deployments.
  • If you need to handle large uploads or throttling, add size limits like app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 to prevent excessive memory or disk usage.
References This workflow gives you an upload endpoint wired to OpenCV processing and a flexible way to vary JPEG quality via form fields or multipart POST parameters.

Watch Video