A Guide To Face Detection With Golang and OpenCV

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

9/10/23, 3:24 PM A guide to Face Detection with Golang and OpenCV

Login

Edward Jackson
4 years ago
A guide to Face Detection with Golang and OpenCV
In this article I’ll be showing you how to get started with gocv and create a simple facial detector
using Haar Cascades.
OpenCV is a library made for computer vision that has been around for almost 20 years. I’ve used
it through college and for personal projects using C++ and Python because it has quite a bit of
support for those languages. But as I was starting to learn and use Go, I wondered if it is possible
to use OpenCV with it. There were a few examples / tutorials on how to use OpenCV with Go but I
found them too hacky or overly complicated. But the wrapper written by the folks at hybridgroup
is the one that I’ve found that’s easiest to use and well documented.
Requirements
Go
OpenCV ( follow the links under installation )
a webcam / camera
Installation
linux : https://gocv.io/getting-started/linux/
macOS : https://gocv.io/getting-started/macos/
windows : https://gocv.io/getting-started/windows/
Example 1
In the first example let’s try create an app to open up a window that displays a video stream using
your webcam.
Let’s first import the libraries we need.
https://morioh.com/a/e8cfdff4d2f1/a-guide-to-face-detection-with-golang-and-opencv 1/18
9/10/23, 3:24 PM A guide to Face Detection with Golang and OpenCV

import (
“log”
“gocv.io/x/gocv”
)

Then let’s create a VideoCapture object using the VideoCaptureDevicefunction. The


VideoCaptureDevice function will allow you to capture a video stream using the webcam. The
function takes in an integer as a parameter which represents the device ID.
webcam, err := gocv.VideoCaptureDevice(0)

if err != nil {
log.Fatalf(“error opening web cam: %v”, err)
}
defer webcam.Close()

Now we create an empty n-dimensional matrix. These matrix will be used to store the images we
read from our camera later.
img := gocv.NewMat()

defer img.Close()

To display the video stream we will need to create a window. This can be done by using the
NewWindow function.
window := gocv.NewWindow(“webcamwindow”)

defer window.Close()

Now let’s get into the fun part.


https://morioh.com/a/e8cfdff4d2f1/a-guide-to-face-detection-with-golang-and-opencv 2/18
9/10/23, 3:24 PM A guide to Face Detection with Golang and OpenCV

Since the video is a continuous stream of images we will have to create an infinite loop and keep
reading from the camera indefinitely. For this we will use the Read method of the VideoCapture
type. This will expect a Mat type ( the matrix we created above ) and it will return a boolean value
indicating if a frame from the VideoCapture was read successfully or not.
for {

if ok := webcam.Read(&img); !ok || img.Empty() {


log.Println(“Unable to read from the webcam”)
continue
}
.
.
.
}

Finally let’s display the frame in the window we created. Then wait 50ms before moving to the
next frame.
window.IMShow(img)

window.WaitKey(50)

when we run the application we will see a new window opens up with the video stream from your
camera.

https://morioh.com/a/e8cfdff4d2f1/a-guide-to-face-detection-with-golang-and-opencv 3/18
9/10/23, 3:24 PM A guide to Face Detection with Golang and OpenCV

package main

import (
"log"

"gocv.io/x/gocv"
)

func main() {
webcam, err := gocv.VideoCaptureDevice(0)
if err != nil {
log.Fatalf("error opening device: %v", err)
}
defer webcam.Close()

img := gocv.NewMat()
defer img.Close()

window := gocv.NewWindow("webcamwindow")
defer window.Close()

for {
if ok := webcam.Read(&img); !ok || img.Empty() {
log.Println("Unable to read from the webcam")
continue
}

window.IMShow(img)
https://morioh.com/a/e8cfdff4d2f1/a-guide-to-face-detection-with-golang-and-opencv 4/18
9/10/23, 3:24 PM A guide to Face Detection with Golang and OpenCV

window.WaitKey(50)
}
}

Example 2
In this example let’s take the previous example and build upon it to detect faces using Haar
Cascades.
But first … what are Haar Cascades ?
In simpler terms Haar cascades are cascading classifiers that are trained based on the Haar
Wavelet technique. It analyzes pixels in an image to detect features in it. To learn more about
Haar-Cascades you can refer to these links.
Viola-Jones object detection framework
Cascading classifiers
Haar-like feature
You can download pre-trained Haar-Cascades in the opencv repository. For this example we will
use the Haar-Cascade that allows us to detect a person’s frontal face.
Let’s create a classifier and feed the pre-trained Haar-Cascade file to the classifier. In this case I
have already downloaded the opencv_haarcascade_frontalface_default.xml into the directory
where our program is located.
harrcascade := “opencv_haarcascade_frontalface_default.xml”

classifier := gocv.NewCascadeClassifier()
classifier.Load(harrcascade)
defer classifier.Close()

Then to detect the faces in the image lets call DetectMultiScale method. This function will take in
frame ( Mat type ) that was just read from the camera and will return an array of Rectangle type.
https://morioh.com/a/e8cfdff4d2f1/a-guide-to-face-detection-with-golang-and-opencv 5/18
9/10/23, 3:24 PM A guide to Face Detection with Golang and OpenCV

The size of the array represents the number of faces the classifier was able to detect in the frame.
Then to make sure we see this detection let’s iterate through the list of rectangles and print the
Rectangle object to the console and create a border around the rectangle that was detected. You
can do this by calling the Rectangle function. This function will take in the Mat that was read by
the camera, a Rectangle object that was returned from the DetectMultiScale method, a color and
a thickness for the border.
for _, r := range rects {

fmt.Println(“detected”, r)
gocv.Rectangle(&img, r, color, 2)
}

And finally, let’s run the application.

https://morioh.com/a/e8cfdff4d2f1/a-guide-to-face-detection-with-golang-and-opencv 6/18
9/10/23, 3:24 PM A guide to Face Detection with Golang and OpenCV

package main

import (
"fmt"
"image/color"
"log"

"gocv.io/x/gocv"
)

func main() {
webcam, err := gocv.VideoCaptureDevice(0)
if err != nil {
log.Fatalf("error opening web cam: %v", err)
}
defer webcam.Close()

img := gocv.NewMat()
defer img.Close()

window := gocv.NewWindow("webcamwindow")
defer window.Close()

harrcascade := "opencv_haarcascade_frontalface_default.xml"
classifier := gocv.NewCascadeClassifier()
classifier.Load(harrcascade)
defer classifier.Close()

color := color.RGBA{0, 255, 0, 0}


for {
if ok := webcam.Read(&img); !ok || img.Empty() {
log.Println("Unable to read from the device")
continue
}

rects := classifier.DetectMultiScale(img)
for _, r := range rects {
fmt.Println("detected", r)
gocv.Rectangle(&img, r, color, 3)
}

https://morioh.com/a/e8cfdff4d2f1/a-guide-to-face-detection-with-golang-and-opencv 7/18
9/10/23, 3:24 PM A guide to Face Detection with Golang and OpenCV

window.IMShow(img)
window.WaitKey(50)
}
}

And there we go ! We have a simple face detector that’s written using Go. I’m planning on
extending this series and build more cool things using Go and OpenCV. Stay tuned for future
articles.
#go #opencv #python

2 Likes 138.30 GEEK

https://morioh.com/a/e8cfdff4d2f1/a-guide-to-face-detection-with-golang-and-opencv 8/18
9/10/23, 3:24 PM A guide to Face Detection with Golang and OpenCV

Edward Jackson
3 days ago
How to Make CSS Cards with Curved Outside Edges
Learn how to create stylish and unique CSS cards with curved outside edges. This step-by-step
tutorial will show you how to use CSS to create a visually appealing and engaging design that will
make your content stand out.
#

YOUTUBE.COM
How to Make CSS Cards with Curved Outside Edges
Learn how to create stylish and unique CSS cards with curved outside edges. This step-by-step tutorial will …
https://morioh.com/a/e8cfdff4d2f1/a-guide-to-face-detection-with-golang-and-opencv 9/18
9/10/23, 3:24 PM A guide to Face Detection with Golang and OpenCV

1.05 GEEK

Edward Jackson
4 days ago
Create Magnetic & Direction-Aware Button Effects with CSS & JavaScript
Make your buttons stand out with magnetic and direction-aware effects using CSS and
JavaScript. This tutorial will teach you how to create buttons that respond to the user's cursor
movement, adding a touch of interactivity and visual interest to your website or app.
# #j i

YOUTUBE.COM
Create Magnetic & Direction-Aware Button Effects with CSS & JavaScript
Make your buttons stand out with magnetic and direction-aware effects using CSS and JavaScript. This tuto…
1.05 GEEK

https://morioh.com/a/e8cfdff4d2f1/a-guide-to-face-detection-with-golang-and-opencv 10/18
9/10/23, 3:24 PM A guide to Face Detection with Golang and OpenCV

Edward Jackson
4 days ago
SQL Tutorial for Beginners: SQL SELECT INTO (Copy Table)
“Learn about SQL SELECT INTO (Copy Table) with the help of examples. Learn how to copy
data from one table to another with the SQL SELECT INTO statement.”
In SQL, the `SELECT INTO` statement is used to copy data from one table to another.

1.10 GEEK

Edward Jackson
5 days ago
.NET 8 Blazor: Render Modes + Demo App Download

https://morioh.com/a/e8cfdff4d2f1/a-guide-to-face-detection-with-golang-and-opencv 11/18
9/10/23, 3:24 PM A guide to Face Detection with Golang and OpenCV

“Learn about the new render modes in .NET 8 Blazor and how to use them to build more
performant and flexible web applications. This article includes a demo app download so you
h d d f lf”

YOUTUBE.COM
.NET 8 Blazor: Render Modes + Demo App Download
Learn about the new render modes in .NET 8 Blazor and how to use them to build more performant and flexi…
1.05 GEEK

Edward Jackson
1 week ago
Le manuel de programmation C pour les débutants
“Apprenez les bases de la programmation C à partir de zéro avec ce manuel complet. Couvre
les variables, les types de données, les opérateurs, les instructions de flux de contrôle, les
fonctions, les bibliothèques, les API, le débogage, les tests et le déploiement.”
1.05 GEEK
https://morioh.com/a/e8cfdff4d2f1/a-guide-to-face-detection-with-golang-and-opencv 12/18
9/10/23, 3:24 PM A guide to Face Detection with Golang and OpenCV

Edward Jackson
1 month ago
How to Add Bullet Points in Excel
“Make your Excel spreadsheets more readable and organized with bullet points. Learn how
to add bullet points in a few simple steps.”
Excel is a powerful spreadsheet program, but it can be difficult to make your data look good. One

YOUTUBE.COM
Add Bullet Points to Your Excel Spreadsheets with Ease
Make your Excel spreadsheets more readable and organized with bullet points. Learn how to add bullet point…
1 Likes 1.40 GEEK

https://morioh.com/a/e8cfdff4d2f1/a-guide-to-face-detection-with-golang-and-opencv 13/18
9/10/23, 3:24 PM A guide to Face Detection with Golang and OpenCV

Edward Jackson
1 month ago
Removing Duplicate Data in Microsoft Excel Spreadsheets
“This article will teach you how to use the Remove Duplicates feature in Excel to remove
duplicate data from your worksheets. Learn how to remove duplicates from your dataset to
help clean up your data before analysis.”

YOUTUBE.COM
Remove Duplicate Data in Excel with Ease
This article will teach you how to use the Remove Duplicates feature in Excel to remove duplicate data from …
1 Likes 1.25 GEEK

Edward Jackson
1 month ago
Como excluir linhas em branco no Excel de forma rápida e fácil
https://morioh.com/a/e8cfdff4d2f1/a-guide-to-face-detection-with-golang-and-opencv 14/18
9/10/23, 3:24 PM A guide to Face Detection with Golang and OpenCV

“Aprenda como excluir linhas em branco no Excel de forma rápida e fácil com este guia
passo a passo!”
Você pode remover automaticamente linhas em branco no Excel selecionando primeiro seu
1.25 GEEK

Edward Jackson
1 month ago
Cyber Security Full course - 11 Hours | Cyber Security Training For Beginners
“Learn cyber security from scratch in this comprehensive course! Master the skills you need
to protect your systems from cyberattacks in just 11 hours.”
This video on "Cyber Security Full Course" will help you understand and learn the fundamentals of

YOUTUBE.COM
Cyber Security Course for Beginners: The Complete Course in 11 Hours
Learn cyber security from scratch in this comprehensive course! Master the skills you need to protect your s…
https://morioh.com/a/e8cfdff4d2f1/a-guide-to-face-detection-with-golang-and-opencv 15/18
9/10/23, 3:24 PM A guide to Face Detection with Golang and OpenCV

1.15 GEEK

Edward Jackson
1 month ago
The Ultimate Guide to Calculating Integrals in Python
“Learn how to calculate definite and indefinite integrals in Python with ease. This article
covers everything you need to know, from the basics to advanced concepts.”
Python is a versatile programming language that offers libraries and tools for scientific computing

13 Likes 1.25 GEEK

https://morioh.com/a/e8cfdff4d2f1/a-guide-to-face-detection-with-golang-and-opencv 16/18
9/10/23, 3:24 PM A guide to Face Detection with Golang and OpenCV

https://morioh.com/a/e8cfdff4d2f1/a-guide-to-face-detection-with-golang-and-opencv 17/18
9/10/23, 3:24 PM A guide to Face Detection with Golang and OpenCV

https://morioh.com/a/e8cfdff4d2f1/a-guide-to-face-detection-with-golang-and-opencv 18/18

You might also like