這段程式碼構建了一個使用 Python `aiohttp` 框架和 `OpenCV` 來實現的 Web 服務器,目的是在兩種不同模式之間切換並進行影像處理或影像傳輸。以下是對程式碼的功能介紹和實現細節的詳細說明。 ### 系統簡章:基於 aiohttp 和 OpenCV 的異步影像處理服務 這份簡章介紹如何利用 Python、OpenCV、aiohttp 以及 TensorFlow Lite 模型來實現一個服務器,該服務器支持即時影像處理和根據用戶請求切換處理模式的功能。 #### 功能概述 1. **模式切換** (`handle_switch`): - 允許用戶通過 HTTP GET 請求來切換當前的運行模式。 - 當前模式在 "A"(AI 驗證)和 "B"(API 傳輸影像)之間切換。 ```python async def handle_switch(request): global current_mode if current_mode == "A": current_mode = "B" else: current_mode = "A" return web.Response(text=f"當前模式已切換到: {current_mode}") ``` 2. **影像推理處理** (`handle_inference`): - 根據當前模式,進行不同的處理流程: - **模式A**: 使用 OpenCV 從攝像頭讀取圖像,並用 TensorFlow Lite 模型進行預測。 - **模式B**: 暫時返回一個等待信息,表示在此模式下等待透過其他方式(例如 HTTP POST)接收圖像。 ```python async def handle_inference(request): global current_mode if current_mode == "A": ret, image = camera.read() if not ret: return web.Response(text="Failed to grab frame", status=500) class_name, confidence_score = model.predict(image) response = { "class": class_name, "confidence_score": str(np.round(confidence_score * 100, 2)) + "%" } else: response = {"message": "API模式,等待影像傳輸..."} return web.json_response(response) ``` #### 伺服器初始化和運行 - 配置並啟動 aiohttp 的 Web 應用。 - 註冊路由以處理 `/switch` 和 `/inference` 路徑的 GET 請求。 ```python async def init_app(): app = web.Application() app.add_routes([ web.get('/switch', handle_switch), web.get('/inference', handle_inference), ]) return app if __name__ == '__main__': model = TFLiteModel("model.tflite", "labels.txt") camera = cv2.VideoCapture(0) web.run_app(init_app(), host='127.0.0.1', port=8080) ``` ### 結論 這個系統利用異步編程提供了一個高效的方式來即時處理和分析來自攝像頭的影像。它適用於需要快速反應和處理影像數據的場景,如監控、實時數據分析和遠程控制等應用。透過簡單的 HTTP 請求,用戶可以方便地控制系統的運行模式,使其更加靈活和實用。 ```python import cv2 import asyncio from aiohttp import web from TFLiteAI import TFLiteModel # 全局變量,用於存儲當前模式 current_mode = "A" # 默認模式為A async def handle_switch(request): global current_mode # 切換模式 if current_mode == "A": current_mode = "B" else: current_mode = "A" return web.Response(text=f"當前模式已切換到: {current_mode}") async def handle_inference(request): global current_mode if current_mode == "A": # 模式A: AI驗證 # 這裡假設已經從攝像頭獲取了圖像,進行AI處理 ret, image = camera.read() if not ret: return web.Response(text="Failed to grab frame", status=500) class_name, confidence_score = model.predict(image) response = { "class": class_name, "confidence_score": str(np.round(confidence_score * 100, 2)) + "%" } else: # 模式B: 透過API傳輸影像,這裡簡化為返回文本消息 response = { "message": "API模式,等待影像傳輸..." } return web.json_response(response) async def init_app(): app = web.Application() app.add_routes([ web.get('/switch', handle_switch), web.get('/inference', handle_inference), ]) return app if __name__ == '__main__': model = TFLiteModel("model.tflite", "labels.txt") camera = cv2.VideoCapture(0) web.run_app(init_app(), host='127.0.0.1', port=8080) ```