使用 Go 请求 YOLOv3 模型进行物体检测

  1. 环境准备
  2. 安装 Go 环境:
    如果你还没有安装 Go,可以通过以下链接下载并安装:

Go 官方下载页面

  1. 使用 HTTP 请求:
    我们将在 Go 程序中使用 net/http 包来发送请求和处理响应。如果你的物体检测模型已经部署为一个 HTTP 服务(例如使用 Python 和 Flask 部署),Go 程序将向该服务发送 HTTP 请求,传递图像并接收检测结果。

  2. 编写 Go 程序
    在本示例中,Go 程序会读取图像文件,将其转换为 Base64 编码,并将其发送到 YOLOv3 物体检测服务,最后接收并打印检测结果。

Go 程序 (yolo_detect.go)
go

package main

import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
)

// 定义响应结构体
type Object struct {
Class string json:"class"
Confidence float64 json:"confidence"
Bbox []int json:"bbox"
}

type Response struct {
Objects []Object json:"objects"
}

func main() {
// 目标 YOLOv3 模型服务的 URL
url := "http://localhost:5000/detect" // 假设服务运行在本地的5000端口

// 读取图像文件并转换为 Base64 编码
imagePath := "test.jpg"
file, err := os.Open(imagePath)
if err != nil {
	log.Fatal("无法打开文件:", err)
}
defer file.Close()

fileBytes, err := ioutil.ReadAll(file)
if err != nil {
	log.Fatal("无法读取文件:", err)
}

// 将图像转换为 Base64 编码
base64Image := base64.StdEncoding.EncodeToString(fileBytes)

// 构建请求体
requestBody := map[string]string{
	"image": base64Image,
}
jsonBody, err := json.Marshal(requestBody)
if err != nil {
	log.Fatal("JSON 编码错误:", err)
}

// 发送 HTTP POST 请求
resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonBody))
if err != nil {
	log.Fatal("请求失败:", err)
}
defer resp.Body.Close()

// 读取响应内容
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
	log.Fatal("读取响应失败:", err)
}

// 解析 JSON 响应
var response Response
if err := json.Unmarshal(body, &response); err != nil {
	log.Fatal("解析响应失败:", err)
}

// 输出检测结果
if len(response.Objects) > 0 {
	fmt.Println("检测结果:")
	for _, object := range response.Objects {
		fmt.Printf("类别: %s, 准确度: %.2f, 边界框: %v\n", object.Class, object.Confidence, object.Bbox)
	}
} else {
	fmt.Println("未检测到任何物体")
}

}
3. 模型服务说明
假设物体检测服务已经通过 Python 和 Flask 部署,接收 POST 请求,并返回 JSON 格式的检测结果。服务的返回数据结构类似于:

json

{
"objects": [
{
"class": "person",
"confidence": 0.98,
"bbox": [100, 150, 200, 250]
},
{
"class": "car",
"confidence": 0.85,
"bbox": [300, 400, 500, 600]
}
]
}
4. 启动物体检测服务
我们可以使用 Python 和 Flask 创建一个简单的 YOLOv3 模型推理服务。以下是一个示例 Flask 服务的实现:

Flask 服务(Python)
python

from flask import Flask, request, jsonify
import cv2
import numpy as np
import base64
import io

app = Flask(name)

加载 YOLO 模型

net = cv2.dnn.readNet("yolov3.weights", "yolov3.cfg")
layer_names = net.getLayerNames()
output_layers = [layer_names[i - 1] for i in net.getUnconnectedOutLayers()]

@app.route('/detect', methods=['POST'])
def detect_objects():
data = request.get_json()
image_data = base64.b64decode(data['image'])

# 转换为 OpenCV 格式
nparr = np.frombuffer(image_data, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

# 物体检测
blob = cv2.dnn.blobFromImage(img, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
net.setInput(blob)
outs = net.forward(output_layers)

# 提取检测到的物体
objects = []
for out in outs:
    for detection in out:
        scores = detection[5:]
        class_id = np.argmax(scores)
        confidence = scores[class_id]
        if confidence > 0.5:
            center_x = int(detection[0] * img.shape[1])
            center_y = int(detection[1] * img.shape[0])
            w = int(detection[2] * img.shape[1])
            h = int(detection[3] * img.shape[0])
            x = int(center_x - w / 2)
            y = int(center_y - h / 2)
            objects.append({
                "class": str(class_id),
                "confidence": float(confidence),
                "bbox": [x, y, x + w, y + h]
            })

return jsonify({"objects": objects})

if name == "main":
app.run(host='0.0.0.0', port=5000)
5. 运行 Go 程序
确保物体检测服务已启动,并且正在监听请求(例如 Flask 服务在本地 5000 端口运行)。然后运行 Go 程序:

bash
更多内容访问ttocr.com或联系1436423940
go run yolo_detect.go
6. 输出结果
Go 程序将会输出 YOLOv3 检测的结果,例如:

makefile

检测结果:
类别: 0, 准确度: 0.98, 边界框: [100, 150, 200, 250]
类别: 2, 准确度: 0.85, 边界框: [300, 400, 500, 600]

posted @   ttocr、com  阅读(23)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示