MareArts ANPR mobile app

12/30/2025

MareArts ANPR HTTP Server Integration - Load Once, Process Fast

πŸš€ MareArts ANPR HTTP Server - Easy Integration for Any Platform

One of the biggest challenges in ANPR (Automatic Number Plate Recognition) integration is the model loading time. Loading deep learning models can take 20+ seconds, which is impractical if you reload them for every image. Today, I'm sharing our solution: a lightweight HTTP server that loads models once and processes images from memory.

πŸ“Š The Problem: Model Loading Overhead

  • Model loading: ~22 seconds (one time)
  • Image processing: ~0.03 seconds per image
  • Traditional approach: Load models for EVERY image = slow!
  • Server approach: Load models ONCE, process thousands of images = fast!

✨ The Solution: Simple HTTP Server

Our simple_server.py creates a FastAPI server that:

  1. Loads ANPR models once at startup
  2. Accepts images through 3 different methods (file upload, raw bytes, base64)
  3. Processes images directly from memory (no disk I/O)
  4. Perfect for integration with C#, Visual Studio, or any HTTP client

πŸ”§ Server Implementation

Here's the core server code:

#!/usr/bin/env python3
from fastapi import FastAPI, File, UploadFile, Request
from fastapi.responses import JSONResponse
from marearts_anpr import ma_anpr_detector_v14, ma_anpr_ocr_v14, marearts_anpr_from_cv2
import cv2
import numpy as np

# ============================================================================
# LOAD MODELS (Once at startup)
# ============================================================================

detector = ma_anpr_detector_v14(
    "medium_640p_fp32", USER, KEY, SIG,
    backend="cpu",  # or "cuda" for GPU
    conf_thres=0.20
)

ocr = ma_anpr_ocr_v14("small_fp32", "eup", USER, KEY, SIG, backend="cpu")

# ============================================================================
# CREATE SERVER
# ============================================================================

app = FastAPI(title="MareArts ANPR Server")

@app.post("/detect")
async def detect_plate_file(image: UploadFile = File(...)):
    """Method 1: Upload image file (multipart/form-data)"""
    image_bytes = await image.read()
    return process_image_bytes(image_bytes)

@app.post("/detect/binary")
async def detect_plate_binary(request: Request):
    """Method 2: Send raw image bytes"""
    image_bytes = await request.body()
    return process_image_bytes(image_bytes)

@app.post("/detect/base64")
async def detect_plate_base64(data: Base64Image):
    """Method 3: Send base64 encoded image"""
    image_bytes = base64.b64decode(data.image)
    return process_image_bytes(image_bytes)

def process_image_bytes(image_bytes):
    """Process image from bytes"""
    nparr = np.frombuffer(image_bytes, np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    result = marearts_anpr_from_cv2(detector, ocr, img)
    return result

πŸ’» Client Examples

Python Client (test_server.py)

import requests

def test_server(image_path, server_url="http://localhost:8000"):
    # Health check
    response = requests.get(f"{server_url}/health")
    print(response.json())
    
    # Detect plates
    with open(image_path, 'rb') as f:
        files = {'image': f}
        response = requests.post(f"{server_url}/detect", files=files)
    
    result = response.json()
    if result.get('results'):
        print(f"✅ Detected {len(result['results'])} plate(s):")
        for plate in result['results']:
            print(f"  • {plate['ocr']} ({plate['ocr_conf']}%)")

cURL Command Line

# Method 1: File upload
curl -X POST http://localhost:8000/detect -F "image=@plate.jpg"

# Method 2: Binary data
curl -X POST http://localhost:8000/detect/binary --data-binary "@plate.jpg"

# Health check
curl http://localhost:8000/health

C# / Visual Studio Integration

using System.Net.Http;

// Example 1: Send raw bytes
var client = new HttpClient();
var content = new ByteArrayContent(imageBytes);
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
var response = await client.PostAsync("http://localhost:8000/detect/binary", content);

// Example 2: Send base64 JSON
var base64Image = Convert.ToBase64String(imageBytes);
var json = JsonSerializer.Serialize(new { image = base64Image });
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://localhost:8000/detect/base64", content);

🎯 Usage Guide

Step 1: Install dependencies

pip install marearts-anpr fastapi uvicorn python-multipart
ma-anpr config  # Configure your credentials

Step 2: Start the server (Terminal 1)

python simple_server.py
# Models load once (~22s), then server waits for requests

Step 3: Send images (Terminal 2 or your application)

python test_server.py your_image.jpg

🌟 Key Benefits

  • Load Once, Use Forever: Models load at startup, not per request
  • Memory Processing: No disk I/O, process images from RAM
  • Multiple Input Methods: File upload, raw bytes, or base64
  • Cross-Platform: Works with Python, C#, JavaScript, or any HTTP client
  • Production Ready: Built on FastAPI with async support
  • Easy Integration: RESTful API with JSON responses

πŸ“ˆ Performance Comparison

Approach First Image Subsequent Images
Traditional (load per image) ~22 seconds ~22 seconds each
HTTP Server (load once) ~22 seconds ~0.03 seconds each

Result: 700x faster for subsequent images! πŸš€

πŸ”— Available Endpoints

  • POST /detect - Upload file (multipart/form-data)
  • POST /detect/binary - Send raw bytes (application/octet-stream)
  • POST /detect/base64 - Send base64 JSON
  • GET / - Server info
  • GET /health - Health check

πŸŽ“ When to Use This

  • ✅ Integrating ANPR into C# / Visual Studio projects
  • ✅ Building web applications with ANPR
  • ✅ Processing multiple images efficiently
  • ✅ Microservice architecture
  • ✅ Real-time video processing

πŸ“¦ Complete Example Package

All code is available in our SDK:

  • simple_server.py - HTTP server (202 lines)
  • test_server.py - Python client test (52 lines)
  • README.md - Complete documentation

Install: pip install marearts-anpr

πŸ” Configuration

The server uses environment variables for credentials:

# Configure once
ma-anpr config

# Credentials are stored in ~/.marearts/.marearts_env
# Server automatically loads from environment variables

πŸ’‘ Conclusion

This HTTP server approach makes ANPR integration incredibly simple. Whether you're building a C# desktop application, a web service, or a microservice architecture, you can now integrate license plate recognition with just a few HTTP calls. No need to worry about Python integration complexity - just send HTTP requests!

The key insight: separate model loading from image processing. Load once, process thousands of times.

Happy coding! πŸš—πŸ“Έ

No comments:

Post a Comment