首先依次安装go、brew、opencv、pkg-config
安装好之后登陆gocv.io网站进行设置
设置好之后
新建go文件,源码如下,运行就完了,带好耳机
package main import ( "bytes" "encoding/binary" "fmt" "github.com/bobertlo/go-mpg123/mpg123" "github.com/gordonklaus/portaudio" "image/color" "log" "time" "gocv.io/x/gocv" ) func main() { // set to use a video capture device 0 deviceID := 0 // open webcam webcam, err := gocv.OpenVideoCapture(deviceID) if err != nil { fmt.Println(err) return } defer webcam.Close() // 新建一个摄像头窗口 window := gocv.NewWindow("Face Detect") defer window.Close() // prepare image matrix img := gocv.NewMat() defer img.Close() // color for the rect when faces detected blue := color.RGBA{120, 120, 255, 0} // load classifier to recognize faces classifier := gocv.NewCascadeClassifier() //haarcascade_frontalface_default.xml if !classifier.Load("data/haarcascade_frontalface_alt2.xml") { fmt.Println("没找到配置文件: data/haarcascade_frontalface_default.xml") return } defer classifier.Close() fmt.Printf("开始读取摄像头数据: %v\n", deviceID) for { if ok := webcam.Read(&img); !ok { fmt.Printf("找不到摄像头 %v\n", deviceID) return } if img.Empty() { continue } // 检测人脸 rects := classifier.DetectMultiScale(img) //fmt.Printf("当前人脸数 %d \n", len(rects)) if len(rects) > 2 { fmt.Println("指点江山激扬文字,你背后有人。。。。。。。。。。。。。", time.Now()) PlayThree("data/aigei.mp3") } // 脸上画个蓝色的方框 for _, r := range rects { gocv.Rectangle(&img, r, blue, 3) } // 显示图片 window.IMShow(img) window.WaitKey(1) } } func PlayThree(filename string) error { portaudio.Initialize() log.Print("播放声音\n") // new 一个解析器 decoder, err := mpg123.NewDecoder("") if err != nil { return err } defer decoder.Delete() //打开文件 if err := decoder.Open(filename); err != nil { return err } defer decoder.Close() //设定音乐格式 rate, channels, _ := decoder.GetFormat() decoder.FormatNone() decoder.Format(rate, channels, mpg123.ENC_SIGNED_16) // 缓冲 out := make([]int16, 8196) // 打开 portaudio 流 stream, err := portaudio.OpenDefaultStream( 0, channels, float64(rate), len(out), &out, ) if err != nil { return err } defer stream.Close() if err := stream.Start(); err != nil { return err } defer stream.Stop() for { audio := make([]byte, 2*len(out)) _, err = decoder.Read(audio) if err != nil { if err == mpg123.EOF { return err } return err } if err = binary.Read(bytes.NewBuffer(audio), binary.LittleEndian, out); err != nil { return err } if err = stream.Write(); err != nil { return err } } return nil }