Detect Faces in a Photo in Go

Cloudmersive
2 min readApr 5, 2021

If you haven’t been living under a rock for the past several years, you’ve probably heard of face detection. However, just in case you missed it, face detection is defined as a specific function that locates and identifies human faces in digital images. The process leverages AI-based computer technology, and can be incredibly helpful for organizations that have a client base who regularly upload photos to a website or app. If your business has a need for facial detection, the following API can be used in Go to automatically detect faces in an image and will support common file formats such as PNG and JPEG.

All you need for the operation is the image file and your API key to input into the following code:

package mainimport (
"fmt"
"bytes"
"mime/multipart"
"os"
"path/filepath"
"io"
"net/http"
"io/ioutil"
)
func main() {url := "https://api.cloudmersive.com/image/face/locate"
method := "POST"
payload := &bytes.Buffer{}
writer := multipart.NewWriter(payload)
file, errFile1 := os.Open("/path/to/file")
defer file.Close()
part1,
errFile1 := writer.CreateFormFile("imageFile",filepath.Base("/path/to/file"))
_, errFile1 = io.Copy(part1, file)
if errFile1 != nil {
fmt.Println(errFile1)
return
}
err := writer.Close()
if err != nil {
fmt.Println(err)
return
}
client := &http.Client {
}
req, err := http.NewRequest(method, url, payload)
if err != nil {
fmt.Println(err)
return
}
req.Header.Add("Content-Type", "multipart/form-data")
req.Header.Add("Apikey", "YOUR-API-KEY-HERE")
req.Header.Set("Content-Type", writer.FormDataContentType())
res, err := client.Do(req)
if err != nil {
fmt.Println(err)
return
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(body))
}

And that’s it! The response will indicate the number of faces and which quadrant they fall under. To retrieve your personal API key, simply head to the Cloudmersive website to register for a free account.

--

--

Cloudmersive

There’s an API for that. Cloudmersive is a leader in Highly Scalable Cloud APIs.