main.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package main
  2. import (
  3. "fmt"
  4. "image/color"
  5. "gocv.io/x/gocv"
  6. )
  7. func main() {
  8. deviceID := 0
  9. // open webcam
  10. webcam, err := gocv.OpenVideoCapture(deviceID)
  11. if err != nil {
  12. fmt.Println(err)
  13. return
  14. }
  15. defer webcam.Close()
  16. // open display window
  17. window := gocv.NewWindow("Face Detect")
  18. defer window.Close()
  19. // prepare image matrix
  20. img := gocv.NewMat()
  21. defer img.Close()
  22. // color for the rect when faces detected
  23. blue := color.RGBA{0, 0, 255, 0}
  24. // load classifier to recognize faces
  25. classifier := gocv.NewCascadeClassifier()
  26. defer classifier.Close()
  27. if !classifier.Load("data/haarcascade_frontalface_default.xml") {
  28. fmt.Println("Error reading cascade file: data/haarcascade_frontalface_default.xml")
  29. return
  30. }
  31. fmt.Printf("start reading camera device: %v\n", deviceID)
  32. for {
  33. if ok := webcam.Read(&img); !ok {
  34. fmt.Printf("cannot read device %v\n", deviceID)
  35. return
  36. }
  37. if img.Empty() {
  38. continue
  39. }
  40. // detect faces
  41. rects := classifier.DetectMultiScale(img)
  42. fmt.Printf("found %d faces\n", len(rects))
  43. // draw a rectangle around each face on the original image
  44. for _, r := range rects {
  45. gocv.Rectangle(&img, r, blue, 3)
  46. }
  47. // show the image in the window, and wait 1 millisecond
  48. window.IMShow(img)
  49. window.WaitKey(1)
  50. }
  51. }