Golang : Detect number of faces or vehicles in a photo
This is a short tutorial on how to use OpenCV to detect the number of faces in an image. Knowing the number of faces in a given photo is crucial in developing machine learning capabilities that involve computer vision.
For examples,
1) A robot needs to know how many people to serve glasses of water.
2) A driverless car needs to know how many incoming cars and number of passengers in the car. IF the drive seat position has a face, chances are the incoming car is in motion.
In this example, we will learn how to detect the number of human faces with a command line Golang program and report the number. If you're looking to detect cars, use the HAAR cascade file for vehicle detection or download the XML files at https://github.com/abhi-kumar/CAR-DETECTION/blob/master/checkcas.xml or http://cogcomp.cs.illinois.edu/Data/Car/
If you need to detect more specific data such as eyes, ears, etc. Use the cascade files at https://github.com/opencv/opencv/tree/master/data/haarcascades.
Here you go!
package main
import (
"fmt"
"github.com/lazywei/go-opencv/opencv"
"image"
gif "image/gif"
_ "image/jpeg"
_ "image/png"
"net/http"
"os"
)
// global variables
var (
cascade = new(opencv.HaarCascade)
)
func errCheck(err error) {
if err != nil {
panic(err)
}
}
func main() {
if len(os.Args) != 2 {
fmt.Printf("Usage : %s <imagefilename>\n", os.Args[0])
os.Exit(0)
}
imageFileName := os.Args[1]
fmt.Println("Analyzing [" + imageFileName + "]......")
// we will use Go's method of load images
// instead of openCV.LoadImage
// because we want to detect if the user supplies animated GIF or not
imageFile, err := os.Open(imageFileName)
errCheck(err)
defer imageFile.Close()
img, _, err := image.Decode(imageFile)
errCheck(err)
buffer := make([]byte, 512)
imageFile.Seek(0, 0) // reset reader
_, err = imageFile.Read(buffer)
errCheck(err)
filetype := http.DetectContentType(buffer)
// check if image is GIF and if yes, check to see if it is animated GIF by
// counting the LoopCount number
fmt.Println("Analyzing image type : ", filetype)
if filetype == "image/gif" {
imageFile.Seek(0, 0)
// warn if image is animated GIF
gif, err := gif.DecodeAll(imageFile)
errCheck(err)
if gif.LoopCount != 0 {
fmt.Println("Animated gif detected. Will only scan for faces in the 1st frame.")
}
}
// for vehicles XML files
// see https://github.com/abhi-kumar/CAR-DETECTION/blob/master/checkcas.xml
// or http://cogcomp.cs.illinois.edu/Data/Car/
cascade = opencv.LoadHaarClassifierCascade("./haarcascade_frontalface_alt.xml")
defer cascade.Release()
// convert Go's image.Image type to OpenCV's IplImage(Intel Image Processing Library)
openCVimg := opencv.FromImage(img)
defer openCVimg.Release()
if openCVimg != nil {
faces := cascade.DetectObjects(openCVimg)
fmt.Printf("Detected [%v] faces in image.\n", len(faces)) // <------- here !
} else {
panic("OpenCV FromImage error")
}
}
Sample output:
./detectfaces input.gif
Analyzing [input.gif]......
Analyzing image type : image/gif
Detected 1 faces in image.
./detectfaces img.gif
Analyzing [img.gif]......
Analyzing image type : image/gif
Animated gif detected. Will only scan for faces in the 1st frame.
Detected [0] faces in image.
References:
https://github.com/opencv/opencv/tree/master/data/haarcascades
http://stackoverflow.com/questions/25775650/golang-async-face-detection
See also : Golang : Surveillance with web camera and OpenCV
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+33.6k Golang : Call a function after some delay(time.Sleep and Tick)
+11.2k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+4.7k Golang : Calculate a pip value and distance to target profit example
+7.1k Golang : Check to see if *File is a file or directory
+31.1k Golang : How to convert(cast) string to IP address?
+21.5k Golang : Use TLS version 1.2 and enforce server security configuration over client
+13.9k Golang : How to pass map to html template and access the map's elements
+4.9k Golang : Experimental Jawi programming language
+51.6k Golang : How to get time in milliseconds?
+16.1k Golang : Test floating point numbers not-a-number and infinite example
+13k Golang : Linear algebra and matrix calculation example
+16.1k Golang : Send email and SMTP configuration example