login

AI 3—Computer Vision

from fastapi import FastAPI
import cv2
import numpy as np
import requests  # 新增:用于拉取网络图片

app = FastAPI()

def detect_red(image_bytes):
    np_arr = np.frombuffer(image_bytes, np.uint8)
    img = cv2.imdecode(np_arr, cv2.IMREAD_COLOR)
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    # 红色HSV阈值
    red_mask = cv2.inRange(hsv, np.array([0, 120, 70]), np.array([10, 255, 255]))
    return cv2.countNonZero(red_mask) > 500

@app.get("/colors")
async def colors(url: str = "http://192.168.43.6/capture"):
    """
    从URL获取图片并检测红色
    - url: 可选参数,默认使用 http://192.168.43.6/capture
    """
    try:
        # 1. 从网络拉取图片
        resp = requests.get(url, timeout=10)
        resp.raise_for_status()  # 请求失败直接抛异常
        
        # 2. 检测红色
        has_red = detect_red(resp.content)
        
        return "Red" if has_red else "No Red"
    
    except Exception as e:
        return f"图片获取/识别失败: {str(e)}"

K10

/*!
 * MindPlus
 * DFRobot, 行空板 K10
 */
#include <DFRobot_Iot.h>
#include "unihiker_k10.h"
#include <DFRobot_HTTPClient.h>
#include "unihiker_k10_webcam.h"
// 创建对象
UNIHIKER_K10 k10;
uint8_t screen_dir=2;
DFRobot_Iot myIot;
DFRobot_HTTPClient http;
unihiker_k10_webcam webcam;


// 主程序开始
void setup() {
	k10.begin();
	Serial.begin(9600);
	k10.initScreen(screen_dir);
	k10.initBgCamerImage();
	k10.setBgCamerImage(false);
	k10.creatCanvas();
	k10.setBgCamerImage(true);
	k10.canvas->canvasText("Ready", 0, 0, 0x0000FF, k10.canvas->eCNAndENFont24, 50, false);
	myIot.wifiConnect("Oldmoon Pura 80 Pro", "98765431");
	while (!myIot.wifiStatus()) {}
	webcam.enableWebcam();
}

void loop() {
    Serial.println(myIot.getWiFiLocalIP());
	delay(1000);
    http.GET("http://192.168.43.8:8000/colors", 10000);
    k10.canvas->canvasClear(1);
    k10.canvas->canvasText(http.getString(), 0, 0, 0x0000FF, k10.canvas->eCNAndENFont24, 50, false);
    k10.canvas->updateCanvas();
    Serial.println(http.getString());
}
login