一、安装go-face库
准备好环境,需要下载go-face库:
go get -u -f github.com/Kagami/go-face
官方源码路径
https://github.com/Kagami/go-face
二、安装dlib库
安装这个库挺费时间的,比编写go代码还要长,目前 作者的环境是windows 10, 64位环境。
1、下载MSYS2,是一款高效专业的类似于linux的开发环境软件,该软件基于Cygwin和MinGW-w64的MSYS进行重写,集合了丰富实用的工具组件。下载地址为MSYS2
2、安装此软件,安装成功后,在windows的“开始”菜单,选择MSYS2 MSYS。
3、在MSYS2超级终端里,输入pacman -Syu,如果提示关闭,就关闭。
4、再执行第二步,重新输入pacman -Syu
5、然后输入,pacman -S mingw-w64-x86_64-gcc mingw-w64-x86_64-dlib,至此你已成功安装了dlib了。
6、如果您已经安装了Go和Git,而且想在MSYS2超级终端使用GO和GIT命令,需要修改msys2_shell.cmd文件,搜索“rem set MSYS2_PATH_TYPE=inherit”,然后修改为set MSYS2_PATH_TYPE=inherit,保存即可。
7、从“开始”菜单,选择并运行MSYS2 MinGW x64,然后进入你的例子代码路径,输入go build main.go编译即可。
三、模型下载

下载三个模型
shape_predictor_5_face_landmarks.dat
dlib_face_recognition_resnet_model_v1.dat
mmod_human_face_detector.dat
四、准备好gocv环境
安装的教程如下:
gocv-go语言调用opencv入门_xinlinhack的博客-CSDN博客_go opencv
使用gocv,更好的处理图片。
五、示例代码
单一人脸:

多人脸图片:

- package main
-
- import (
- "fmt"
- "github.com/Kagami/go-face"
- "gocv.io/x/gocv"
- "image"
- "image/color"
- "log"
- "path/filepath"
- )
-
- //
- const (
- dataDir = "models"
- imageDir = "images"
- )
-
-
-
- func main() {
-
- // 特征值
- var descriptor face.Descriptor
-
- // 目标距离
- matchDistance := 0.1
-
- // 创建一个窗口
- window := gocv.NewWindow("dlib Recognize")
- defer window.Close()
-
- // 颜色
- greenColor := color.RGBA{0, 255, 0, 255}
- redColor := color.RGBA{255, 0, 0, 255}
-
-
- // 加载模型
- rec, err := face.NewRecognizer(dataDir)
-
- if err != nil {
- log.Fatal(err)
- }
-
- defer rec.Close()
-
- // 单一脸图片
- faceImagePath := filepath.Join(imageDir, "face.jpg")
-
- img1 := gocv.IMRead(faceImagePath, gocv.IMReadColor)
- defer img1.Close()
-
- fmt.Println("正在读的单一脸图像 = ", faceImagePath)
-
- //
- faces, err := rec.RecognizeFile(faceImagePath)
-
- if err != nil {
- log.Fatalf("无法识别: %v", err)
- }
-
- if 0 == len(faces){
- log.Fatal("图片没有人脸")
- }
-
- for _, f := range faces{
- descriptor = f.Descriptor
- }
-
-
- // 多人脸图片
- facesImagePath := filepath.Join(imageDir, "faces.jpg")
-
- img2 := gocv.IMRead(facesImagePath, gocv.IMReadColor)
- defer img2.Close()
-
- // copy bg to draw
- background := img2.Clone()
- defer background.Close()
-
-
- //
- fmt.Println("正在读的多人脸图像 = ", facesImagePath)
-
- //
- faces, err = rec.RecognizeFile(facesImagePath)
-
- if err != nil {
- log.Fatalf("无法识别: %v", err)
- }
-
- if 0 == len(faces){
- log.Fatal("图片没有人脸")
- }
-
- for _, f := range faces{
-
- gocv.Rectangle(&background, f.Rectangle, redColor, 3)
-
- // 计算特征值之间的欧拉距离
- dist := face.SquaredEuclideanDistance(f.Descriptor, descriptor)
-
- fmt.Println("欧拉距离 = ", dist)
-
- c := redColor
-
- if dist < matchDistance {
- c = greenColor
- }
-
- // 在图片上画人脸框
- pt := image.Pt(f.Rectangle.Min.X, f.Rectangle.Min.Y-20)
- gocv.PutText(&background, "jay", pt, gocv.FontHersheyPlain, 2, c, 2)
-
- }
-
-
- // 显示图片
- window.IMShow(background)
-
- for{
- if window.WaitKey(1) >= 0 {
- break
- }
- }
-
- }
最终输出如下,绿色表示找到的人脸图片。

代码下载:go的dlib例子代码-深度学习文档类资源-CSDN下载