A guide to Face Detection with Golang and OpenCV

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.

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.

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.

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.

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)
		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. 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.

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)
		}

		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.

OpenCV Python Tutorial - Computer Vision With OpenCV In Python

OpenCV Python Tutorial - Computer Vision With OpenCV In Python

In this OpenCV Python Tutorial article, we will be covering various aspects of Computer Vision using OpenCV in Python. OpenCV has been a vital part in the development of software for a long time. Learning OpenCV is a good asset to the developer to improve aspects of coding and also helps in building a software development career.


We will be checking out the following concepts:

  • What is Computer Vision?
  • How a computer reads an image?
  • What is OpenCV?
  • Basics of OpenCV
  • Image Detection using OpenCV
  • Motion Detector using OpenCV

What Is Computer Vision?

To simplify the answer to this — Let us consider a scenario.

We all use Facebook, correct? Let us say you and your friends went on a vacation and you clicked a lot of pictures and you want to upload them on Facebook and you did. But now, wouldn’t it take so much time just to find your friends faces and tag them in each and every picture? Well, Facebook is intelligent enough to actually tag people for you.

So, how do you think the auto tag feature works? In simple terms, it works on computer vision.

Computer Vision is an interdisciplinary field that deals with how computers can be made to gain a high-level understanding from digital images or videos.

The idea here is to automate tasks that the human visual systems can do. So, a computer should be able to recognize objects such as that of a face of a human being or a lamppost or even a statue.


How Does A Computer Read An Image?

Consider the below image:

We can figure out that it is an image of the New York Skyline. But, can a computer find this out all on its own? The answer is no!

The computer reads any image as a range of values between 0 and 255.

For any color image, there are 3 primary channels — Red, green and blue. How it works is pretty simple.

A matrix is formed for every primary color and later these matrices combine to provide a Pixel value for the individual R, G, B colors.

Each element of the matrices provide data pertaining to the intensity of brightness of the pixel.

Consider the following image:

As shown, the size of the image here can be calculated as B x A x 3.

Note: For a black-white image, there is only one single channel.

Next in this article, let us look at what OpenCV actually is.


What Is OpenCV?

OpenCV is a Python library which is designed to solve computer vision problems. OpenCV was originally developed in 1999 by Intel but later it was supported by Willow Garage.

OpenCV supports a wide variety of programming languages such as C++, Python, Java etc. Support for multiple platforms including Windows, Linux, and MacOS.

OpenCV Python is nothing but a wrapper class for the original C++ library to be used with Python. Using this, all of the OpenCV array structures gets converted to/from NumPy arrays.

This makes it easier to integrate it with other libraries which use NumPy. For example, libraries such as SciPy and Matplotlib.

Next in this article, let us look at some of the basic operations that we can perform with OpenCV.


Basic Operations With OpenCV?

Let us look at various concepts ranging from loading images to resizing them and so on.


Loading an image using OpenCV:

Import cv2
# colored Image
Img = cv2.imread (“Penguins.jpg”,1)
# Black and White (gray scale)
Img_1 = cv2.imread (“Penguins.jpg”,0))

As seen in the above piece of code, the first requirement is to import the OpenCV module.

Later we can read the image using imread module. The 1 in the parameters denotes that it is a color image. If the parameter was 0 instead of 1, it would mean that the image being imported is a black and white image. The name of the image here is ‘Penguins’. Pretty straightforward, right?


Image Shape/Resolution:

We can make use of the shape sub-function to print out the shape of the image. Refer below.

Import cv2
# Black and White (gray scale)
Img = cv2.imread (“Penguins.jpg”,0)
Print(img.shape)

By shape of the image, we mean the shape of the NumPy array. As you see from executing the code, the matrix consists of 768 rows and 1024 columns.


Displaying the image:

Displaying an image using OpenCV is pretty simple and straightforward. Refer below.

import cv2
# Black and White (gray scale)
Img = cv2.imread (“Penguins.jpg”,0)
cv2.imshow(“Penguins”, img)
cv2.waitKey(0)
# cv2.waitKey(2000)
cv2.destroyAllWindows()

As you can see, we first import the image using imread. We require a window output to display the images, right?

We use the imshow function to display the image by opening a window. There are 2 parameters to theimshow function which is the name of the window and the image object to be displayed.

Later, we wait for a user event. waitKey makes the window static until the user presses a key. The parameter passed to it is the time in milliseconds.

And lastly, we use destroyAllWindows to close the window based on the waitForKey parameter.


Resizing the image:

Similarly, resizing an image is very easy. Here’s another code snippet:

import cv2
# Black and White (gray scale)
img = cv2.imread (“Penguins.jpg”,0)
resized_image = cv2.resize(img, (650,500))
cv2.imshow(“Penguins”, resized_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Here, resize function is used to resize an image to the desired shape. The parameter here is the shape of the new resized image.

Later, do note that the image object changes from img to resized_image, because of the image object changes now.

Rest of the code is pretty simple to the previous one, correct?

I am sure you guys are curious to look at the penguins, right? This is the image we were looking to output all this while!

There is another way to pass the parameters to the resize function. Refer below.

Resized_image = cv2.resize(img, int(img.shape[1]/2), int(img.shape[0]/2)))

Here, we get the new image shape to be half of that of the original image.

Next up in this article, let us look at how we perform face detection using OpenCV.


Face Detection Using OpenCV

This seems complex at first but it is very easy. Let me walk you through the entire process and you will feel the same.

Step 1: Considering our prerequisites, we will require an image, to begin with. Later we need to create a cascade classifier which will eventually give us the features of the face.

Step 2: This step involves making use of OpenCV which will read the image and the features file. So at this point, there are NumPy arrays at the primary data points.

All we need to do is to search for the row and column values of the face NumPy ndarray. This is the array with the face rectangle coordinates.

Step 3: This final step involves displaying the image with the rectangular face box.

Check out the following image, here I have summarized the 3 steps in the form of an image for easier readability:

Pretty straightforward, correct?

First, we create a CascadeClassifier object to extract the features of the face as explained earlier. The path to the XML file which contains the face features is the parameter here.

The next step would be to read an image with a face on it and convert it into a black and white image using COLOR_BGR2GREY. Followed by this, we search for the coordinates for the image. This is done using detectMultiScale.

What coordinates, you ask? It’s the coordinates for the face rectangle. The scaleFactor is used to decrease the shape value by 5% until the face is found. So, on the whole — Smaller the value, greater is the accuracy.

Finally, the face is printed on the window.


Adding the rectangular face box:

This logic is very simple — As simple as making use of a for loop statement. Check out the following image.

We define the method to create a rectangle using cv2.rectangle by passing parameters such as the image object, RGB values of the box outline and the width of the rectangle.

Let us check out the entire code for face detection:

import cv2
# Create a CascadeClassifier Object
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
# Reading the image as it is
img = cv2.imread("photo.jpg")
# Reading the image as gray scale image
gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Search the co-ordintes of the image
faces = face_cascade.detectMultiScale(gray_img, scaleFactor = 1.05,
                                      minNeighbors=5)
for x,y,w,h in faces:
    img = cv2.rectangle(img, (x,y), (x+w,y+h),(0,255,0),3)
resized = cv2.resize(img, (int(img.shape[1]/7),int(img.shape[0]/7)))
cv2.imshow("Gray", resized)
cv2.waitKey(0) 
cv2.destroyAllWindows()

Next up in this article, let us look at how to use OpenCV to capture video with the computer webcam.


Capturing Video Using OpenCV

Capturing videos using OpenCV is pretty simple as well. the following loop will give you a better idea. Check it out:

The images are read one-by-one and hence videos are produced due to fast processing of frames which makes the individual images move.


Capturing Video:

Check out the following image:

First, we import the OpenCV library as usual. Next, we have a method called VideoCapture which is used to create the VideoCapture object. This method is used to trigger the camera on the user’s machine. The parameter to this function denotes if the program should make use of the built-in camera or an add-on camera. ‘0’ denotes the built-in camera in this case.

And lastly, the release method is used to release the camera in a few milliseconds.

When you go ahead and type in and try to execute the above code, you will notice that the camera light switches on for a split second and turns off later. Why does this happen?

This happens because there is no time delay to keep the camera functional.

Looking at the above code, we have a new line called time.sleep(3) — This makes the script to stop for 3 seconds. Do note that the parameter passed is the time in seconds. So, when the code is executed, the webcam will be turned on for 3 seconds.


Adding the window:

Adding a window to show the video output is pretty simple and can be compared to the same methods used for images. However, there is a slight change. Check out the following code:

I am pretty sure you can make the most sense from the above code apart from one or two lines.

Here, we have defined a NumPy array which we use to represent the first image that the video captures — This is stored in the frame array.

We also have check — This is a boolean datatype which returns True if Python is able to access and read the VideoCapture object.

Check out the output below:

As you can check out, we got the output as True and the part of the frame array is printed.

But we need to read the first frame/image of the video to begin, correct?

To do exactly that, we need to first create a frame object which will read the images of the VideoCapture object.

As seen above, the imshow method is used to capture the first frame of the video.

All this while, we have tried to capture the first image/frame of the video but directly capturing the video.

So how do we go about capturing the video instead of the first image in OpenCV?


Capturing Video Directly:

In order to capture the video, we will be using the while loop. While condition will be such that, until unless ‘check’ is True. If it is, then Python will display the frames.

Here’s the code snippet image:

We make use of the cvtColor function to convert each frame into a grey-scale image as explained earlier.

waitKey(1) will make sure to generate a new frame after every millisecond of a gap.

It is important here that you note that the while loop is completely in play to help iterate through the frames and eventually display the video.

There is a user event trigger here as well. Once the ‘q’ key is pressed by the user, the program window closes.

OpenCV is pretty easy to grasp, right? I personally love how good the readability is and how quickly a beginner can get started working with OpenCV.

Next up in this article, let us look at how to use a very interesting motion detector use case using OpenCV.


Use Case: Motion Detector Using OpenCV

Problem Statement:

You have been approached by a company that is studying human behavior. Your task is to give them a webcam, that can detect the motion or any movement in front of it. This should return a graph, this graph should contain how long the human/object was in front of the camera.

So, now that we have defined our problem statement, we need to build a solution logic to approach the problem in a structured way.

Consider the below diagram:

Initially, we save the image in a particular frame.

The next step involves converting the image to a Gaussian blur image. This is done so as to ensure we calculate a palpable difference between the blurred image and the actual image.

At this point, the image is still not an object. We define a threshold to remove blemishes such as shadows and other noises in the image.

Borders for the object are defined later and we add a rectangular box around the object as we discussed earlier on the blog.

Lastly, we calculate the time at which the object appears and exits the frame.

Pretty easy, right?

Here’s the code snippet:

The same principle follows through here as well. We first import the package and create the VideoCapture object to ensure we capture video using the webcam.

The while loop iterates through the individual frames of the video. We convert the color frame to a grey-scale image and later we convert this grey-scale image to Gaussian blur.

We need to store the first image/frame of the video, correct? We make use of the if statement for this purpose alone.

Now, let us dive into a little more code:

We make use of the absdiff function to calculate the difference between the first occurring frame and all the other frames.

The threshold function provides a threshold value, such that it will convert the difference value with less than 30 to black. If the difference is greater than 30 it will convert those pixels to white color. THRESH_BINARY is used for this purpose.

Later, we make use of the findContours function to define the contour area for our image. And we add in the borders at this stage as well.

The contourArea function, as previously explained, removes the noises and the shadows. To make it simple, it will keep only that part white, which has an area greater than 1000 pixels as we’ve defined for that.

Later, we create a rectangular box around our object in the working frame.

And followed by this is this simple code:

As discussed earlier, the frame changes every 1 millisecond and when the user enters ‘q’, the loop breaks and the window closes.

We’ve covered all of the major details on this OpenCV Python Tutorial blog. One thing that remains with our use-case is that we need to calculate the time for which the object was in front of the camera.


Calculating the time:

We make use of DataFrame to store the time values during which object detection and movement appear in the frame.

Followed by that is VideoCapture function as explained earlier. But here, we have a flag bit we call status. We use this status at the beginning of the recording to be zero as the object is not visible initially.

We will change the status flag to 1 when the object is being detected as shown in the above figure. Pretty simple, right?

We are going to make a list of the status for every scanned frame and later record the date and time using datetime in a list if and where a change occurs.

And we store the time values in a DataFrame as shown in the above explanatory diagram. We’ll conclude by writing the DataFrame to a CSV file as shown.


Plotting the Motion Detection Graph:

The final step in our use-case to display the results. We are displaying the graph which denotes the motion on 2-axes. Consider the below code:

To begin with, we import the DataFrame from the motion_detector.py file.

The next step involves converting time to a readable string format which can be parsed.

Lastly, the DataFrame of time values is plotted on the browser using Bokeh plots.

Output:

I hope this article helps you in learning all the fundamentals needed to get started with OpenCV using Python.

This will be very handy when you are trying to develop applications that require image recognition and similar principles. Now, you should also be able to use these concepts to develop applications easily with the help of OpenCV in Python.

Originally published at www.edureka.co


Learn More

Complete Python: Go from zero to hero in Python

Computer Vision Using OpenCV

Learn Python 3 Programming for Beginners

An A-Z of useful Python tricks

A Complete Machine Learning Project Walk-Through in Python

A Feature Selection Tool for Machine Learning in Python

Learning Python: From Zero to Hero

Automated Machine Learning on the Cloud in Python

MongoDB with Python Crash Course - Tutorial for Beginners

Complete Python Bootcamp: Go from zero to hero in Python 3

Complete Python Masterclass

Python and Django Full Stack Web Developer Bootcamp


OpenCV Python Tutorial: Computer Vision With OpenCV In Python

OpenCV Python Tutorial: Computer Vision With OpenCV In Python

Learn Vision Includes all OpenCV Image Processing Features with Simple Examples. Face Detection, Face Recognition

OpenCV Python Tutorial: Computer Vision With OpenCV In Python

A guide to Face Detection in Python

Face Detection using Open-CV

A guide to Face Detection with Golang and OpenCV

Implement Face Detection Using Python

Python Face Detection Tutorial for Beginners

Computer Vision is an AI based, that is, Artificial Intelligence based technology that allows computers to understand and label images. Its now used in Convenience stores, Driver-less Car Testing, Security Access Mechanisms, Policing and Investigations Surveillance, Daily Medical Diagnosis monitoring health of crops and live stock and so on and so forth..

A common example will be face detection and unlocking mechanism that you use in your mobile phone. We use that daily. That is also a big application of Computer Vision. And today, top technology companies like Amazon, Google, Microsoft, Facebook etc are investing millions and millions of Dollars into Computer Vision based research and product development.

Computer vision allows us to analyze and leverage image and video data, with applications in a variety of industries, including self-driving cars, social network apps, medical diagnostics, and many more.

As the fastest growing language in popularity, Python is well suited to leverage the power of existing computer vision libraries to learn from all this image and video data.

What you'll learn

  • Use OpenCV to work with image files
  • Perform image manipulation with OpenCV, including smoothing, blurring, thresholding, and morphological operations.
  • Create Face Detection Software
  • Detect Objects, including corner, edge, and grid detection techniques with OpenCV and Python
  • Use Python and Deep Learning to build image classifiers
  • Use Python and OpenCV to draw shapes on images and videos
  • Create Color Histograms with OpenCV
  • Study from MIT notes and get Interview questions
  • Crack image processing limits by developing Applications.

Complete Python Course Go from zero to hero in Python

Complete Python Course Go from zero to hero in Python

Complete Python Course Go from zero to hero in Python

Description
Welcome to the Complete Python Course!

This course will take you from Zero to Hero in Python, easily and smartly. We've crafted every piece of content to be concise and straightforward, while never leaving you confused. This course will dive right into Python and get you productive from the very beginning. This is the most comprehensive, yet straight-forward, course for the Python programming language on Simpliv! Whether you have never programmed before, already know basic syntax, or want to learn about the advanced features of Python, this course is for you! In this course we will teach you Python 3. (Note, we also provide older Python 2 notes in case of you need them)

Why Learn Python?

Python is a general-purpose language, which means it can be used to build just about anything,which will be made easy with the right tools/libraries. Professionally, Python is great for backend web development, data analysis, artificial intelligence, and scientific computing. Many developers have also used Python to build productivity tools, games, and desktop apps, so there are plenty of resources to help you learn how to do those as well.

To read more: