face_go

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 19, 2025 License: MIT Imports: 11 Imported by: 0

README

face-go

Translate to:简体中文

A face recognition library based on insightface, implemented using Go + OpenCV + ONNX Runtime, supporting cross-platform usage.

This project uses the buffalo_l model from insightface, providing face detection and feature extraction capabilities. It is suitable for identity verification, face comparison, face clustering, and similar scenarios.


Features

  • Multi-platform support: macOS / Linux / Windows
  • Model inference accelerated by ONNXRuntime
  • Supports reading images and extracting face feature vectors
  • Uses OpenCV for affine transformation alignment
  • Provides a user-friendly Go interface for integration with other modules
  • Usable in face comparison, face clustering, and other tasks

Dependencies

Name macOS / Linux Windows
Go ≥ 1.20 ≥ 1.20
OpenCV Recommend opencv4 + pkg-config Manually install OpenCV and set paths
ONNX Runtime v1.22.0 v1.22.0

Quick Start

1. Install Dependencies
macOS (Homebrew):
brew install go opencv pkg-config
Ubuntu / Debian:
sudo apt update
sudo apt install -y golang libopencv-dev pkg-config
Windows:

Install OpenCV and add the include and lib directories to your system environment variables.

Recommended: download a precompiled version from OpenCV Releases

Download ONNX Runtime

Download and extract the official release v1.22.0: microsoft onnxruntime v1.22.0 After extraction, add the include/ and lib/ paths to your environment variables.

macOS/Linux example:

export CGO_CPPFLAGS="-I/path/to/onnxruntime/include"
export CGO_LDFLAGS="-L/path/to/onnxruntime/lib"
export DYLD_LIBRARY_PATH="/path/to/onnxruntime/lib:$DYLD_LIBRARY_PATH"  # macOS
export LD_LIBRARY_PATH="/path/to/onnxruntime/lib:$LD_LIBRARY_PATH"      # Linux

Windows notes:

Windows does not support pkg-config; you must configure OpenCV and ONNXRuntime paths manually.

set OPENCV_INC_PATH=C:\opencv\build\include
set OPENCV_LIB_PATH=C:\opencv\build\x64\mingw\lib
set CGO_CPPFLAGS=-IC:\onnxruntime\include
set CGO_LDFLAGS=-LC:\onnxruntime\lib -lopencv_core -lopencv_imgproc -lopencv_calib3d

Modify C:\opencv and C:\onnxruntime based on your actual installation paths.

Download Model
wget https://github.com/deepinsight/insightface/releases/download/v0.7/buffalo_l.zip
unzip buffalo_l.zip

Build

You need to enable CGO and link to OpenCV and ONNX Runtime based on your platform.

go build .

If the build fails, make sure CGO_CPPFLAGS, CGO_LDFLAGS, and your dynamic libraries are correctly configured and discoverable by the system.

Example

package main

import (
	facego "github.com/123cdxcc/face-go"
	"github.com/disintegration/imaging"
	"io"
	"os"
	"fmt"
    "log"
)

func main() {
	facego.InitOnnxRuntime("./onnxruntime-osx-arm64-1.22.0/lib/libonnxruntime.1.22.0.dylib")
	if err := facego.LoadOnnxModel("./buffalo_l"); err != nil {
		log.Fatal("Load model fail: ", err.Error())
	}
	defer facego.Cleanup()
	f, err := os.Open("a.jpg")
	if err != nil {
		panic(err)
	}
	faceVector, err := FeaturesInfer(f)
	if err != nil {
		return
	}
	fmt.Println(faceVector)
}

func FeaturesInfer(f io.Reader) ([]float32, error) {
	srcImg, err := imaging.Decode(f)
	if err != nil {
		return nil, err
	}
	_, kpss, err := facego.FaceDetect(srcImg)
	if err != nil {
		return nil, err
	}
	if len(kpss) == 0 {
		return nil, fmt.Errorf("no face detected")
	}
	data, _, err := facego.FaceFeatures(srcImg, kpss[0])
	if err != nil {
		return nil, err
	}
	return data, nil
}

Common Issues

dyld: Library not loaded: @rpath/libonnxruntime.dylib

Reason: macOS does not automatically read DYLD_LIBRARY_PATH when running go run generated binaries.

Solution 1:
go build -o face .
install_name_tool -add_rpath $(pwd)/onnxruntime-osx-universal2-1.12.1/lib face
./arcface
Solution 2:

When developing with GoLand or other IDEs, add the environment variables to your run configuration so you can run directly.

ld: warning: ignoring duplicate libraries: '-lopencv_core'

Reason: OpenCV libraries are linked more than once. Usually harmless.

Suggestion:

  • Use pkg-config to automatically generate dependency flags instead of manually adding -lopencv_*
  • Or safely ignore the warning

References

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Cleanup

func Cleanup()

func ComputeDistance

func ComputeDistance(a, b []float32) (float64, error)

ComputeDistance 计算欧几里得距离 (作为余弦相似度的补充度量)

func Cosine

func Cosine(a []float32, b []float32) (float64, error)

Cosine 为了向后兼容保留的函数,但修复了符号错误

func CosineSimilarity

func CosineSimilarity(a []float32, b []float32) (float64, error)

CosineSimilarity 计算两个向量的余弦相似度 (修复版本)

func FaceDetect

func FaceDetect(src image.Image) ([][]float32, [][]float32, error)

FaceDetect 检测人脸, 返回脸框和人脸关键点,按预测分数排序从高到低。

func FaceFeatures

func FaceFeatures(src image.Image, lmk []float32) ([]float32, image.Image, error)

FaceFeatures 获取人脸特征 src: 源图片 lmk: 人脸关键点 return: 特征向量,人脸图片

func InitOnnxRuntime

func InitOnnxRuntime(onnxRuntimeDylibPath string) error

InitOnnxRuntime 初始化onnxruntime

func L2Normalize

func L2Normalize(vector []float32) []float32

L2Normalize 对特征向量进行L2归一化

func LoadOnnxModel

func LoadOnnxModel(onnxModelPath string) (err error)

LoadOnnxModel 加载infightface的buffalo_l模型,读取det_10g.onnx和w600k_r50.onnx, onnxModelPath: onnx模型目录路径

Types

type FaceCompareResult

type FaceCompareResult struct {
	Similarity   float64 // 相似度 [0, 1]
	IsSamePerson bool    // 是否为同一人
	Confidence   string  // 置信度描述
}

FaceCompareResult 人脸比较结果

func CompareFaces

func CompareFaces(feature1, feature2 []float32, threshold float64) (*FaceCompareResult, error)

CompareFaces 比较两个人脸特征,返回详细的比较结果

func CompareWithDefaultThreshold

func CompareWithDefaultThreshold(feature1, feature2 []float32) (*FaceCompareResult, error)

CompareWithDefaultThreshold 使用默认阈值比较人脸 ArcFace模型的推荐阈值通常在0.6-0.7之间

type TensorValue

type TensorValue struct {
	Value interface{}
	Shape []int64
}

Directories

Path Synopsis
Package to provide some OpenCV functions required in arcface inference.
Package to provide some OpenCV functions required in arcface inference.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL