使用 Go 语言与 OpenCV 进行物体检测

GoCV 是一个 Go 语言绑定的 OpenCV 库,我们可以用它来处理图像、视频并进行物体检测。通过 GoCV,我们能够加载预训练的 YOLO 模型,并在实时视频流中进行物体检测。

环境准备

  1. 安装 GoCV 库
    首先,我们需要安装 GoCV。GoCV 是 Go 语言的 OpenCV 绑定,可以通过以下命令安装:

bash

安装 GoCV

go get -u -d gocv.io/x/gocv
此外,我们还需要安装 OpenCV 库。具体的安装方法可以参考 GoCV 的 官方安装文档.

  1. 下载 YOLO 配置和权重文件
    与其他语言类似,YOLO 模型需要配置文件(.cfg)和权重文件(.weights)。下载 YOLOv3 的配置文件和权重文件:

YOLOv3 配置文件:yolov3.cfg
YOLOv3 权重文件:yolov3.weights
代码实现
下面是用 Go 语言和 GoCV 实现物体检测的代码。

go

package main

import (
"fmt"
"gocv.io/x/gocv"
"gocv.io/x/gocv/contrib"
"image"
)

const (
CONFIDENCE_THRESHOLD = 0.5
NMS_THRESHOLD = 0.4
INPUT_WIDTH = 416
INPUT_HEIGHT = 416
)

func main() {
// 加载 YOLO 模型
net := gocv.ReadNet("yolov3.cfg", "yolov3.weights")
defer net.Close()

// 打开摄像头
webcam, err := gocv.VideoCaptureDevice(0)
if err != nil {
fmt.Println("错误: 无法打开摄像头!")
return
}
defer webcam.Close()

// 创建窗口
window := gocv.NewWindow("物体检测")
defer window.Close()

// 创建图像矩阵
img := gocv.NewMat()
defer img.Close()

// 视频流处理
for {
if ok := webcam.Read(&img); !ok {
fmt.Println("无法从摄像头读取图像")
return
}
if img.Empty() {
continue
}

// 创建 blob 进行输入处理
blob := gocv.BlobFromImage(img, 1.0/255.0, image.Pt(INPUT_WIDTH, INPUT_HEIGHT), gocv.NewScalar(0, 0, 0, 0), true, false)
defer blob.Close()

// 将输入数据传递给模型
net.SetInput(blob, "")

// 获取输出层
layerNames := net.GetLayerNames()
outputLayer := net.GetUnconnectedOutLayersNames()

// 执行前向推理
outputs := net.Forward(outputLayer)

// 进行后处理,提取物体框
boxes, confidences, classIds := postprocess(img, outputs)

// 对检测框进行非最大抑制
indices := gocv.NMSBoxes(boxes, confidences, CONFIDENCE_THRESHOLD, NMS_THRESHOLD)

// 绘制检测框和标签
for _, i := range indices {
box := boxes[i]
gocv.Rectangle(&img, box, gocv.NewScalar(0, 255, 0, 0), 2)
label := fmt.Sprintf("Object: %.2f", confidences[i])
gocv.PutText(&img, label, image.Pt(box.Min.X, box.Min.Y-10), gocv.FontHersheyPlain, 1.0, gocv.NewScalar(0, 255, 0, 0), 2)
}

// 显示结果
window.IMShow(img)
if window.WaitKey(1) >= 0 {
break
}
}
}

// 后处理函数:提取物体框
func postprocess(frame gocv.Mat, outs []gocv.Mat) ([]image.Rectangle, []float32, []int) {
var boxes []image.Rectangle
var confidences []float32
var classIds []int

for _, out := range outs {
data := out.DataPtr()
for i := 0; i < out.Rows(); i++ {
score := data[i*out.Cols():]
confidence := score[5]
if confidence > CONFIDENCE_THRESHOLD {
centerX := int(score[0] * float32(frame.Cols()))
centerY := int(score[1] * float32(frame.Rows()))
width := int(score[2] * float32(frame.Cols()))
height := int(score[3] * float32(frame.Rows()))
box := image.Rect(centerX-width/2, centerY-height/2, centerX+width/2, centerY+height/2)

boxes = append(boxes, box)
confidences = append(confidences, confidence)
classIds = append(classIds, int(score[4]))
}
}
}
return boxes, confidences, classIds
}
说明更多内容访问ttocr.com或联系1436423940

  1. 代码解析
    加载 YOLO 模型:通过 gocv.ReadNet() 加载 YOLO 配置文件和权重文件。
    视频捕捉:使用 gocv.VideoCaptureDevice(0) 打开摄像头进行视频捕捉。
    图像预处理:使用 gocv.BlobFromImage() 函数将图像转为适合 YOLO 模型输入的格式。
    物体检测:使用 net.Forward() 函数进行前向推理,得到检测结果。
    后处理:通过 postprocess() 函数提取物体框、置信度和类别标签,并绘制边界框。
  2. 注意事项
    在使用 GoCV 时,确保已经正确安装了 OpenCV 和 GoCV。
    YOLO 模型的配置文件和权重文件必须下载并放置在正确的路径下。
posted @ 2024-12-03 11:28  ttocr、com  阅读(722)  评论(0)    收藏  举报