Example 2: Face Detection with OpenCV
Introduction
This example uses the OpenCV WebCam Python script and adds a basic face detection.
Steps to do
Open Example 1
Add the macro module developed in Example 1 to your workspace.
Download trained classifier XML file
Initially you need to download the trained classifier XML file. It is available in the OpenCV GitHub repository. Save the file somewhere and remember the path for later usage in Python.
Extend Python file
Right click on your module , open the context menu and select [ Related Files → <YOUR_MODULE_NAME>.py ]. The text editor MATE opens. You can see the Python file of your module.
You have to load the previously downloaded XML file first.
<YOUR_MODULE_NAME>.py
# from mevis import *
import cv2
import OpenCVUtils
_interfaces = []
camera = None
face_cascade = cv2.CascadeClassifier('<YOUR_PATH>/haarcascade_frontalface_default.xml')
After loading the file, go to the previously implemented grabImage function and extend it as follows:
<YOUR_MODULE_NAME>.py
def grabImage():
_, img = camera.read()
updateImage(img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
# Display the output
cv2.imshow('img', img)
In the end, destroy all OpenCV windows in releaseCamera function.
<YOUR_MODULE_NAME>.py
def releaseCamera(_):
global camera, _interfaces
ctx.removeTimers()
_interfaces = []
if camera:
camera.release()
camera = None
cv2.destroyAllWindows()
Opening your macro module and pressing Start should now open your WebCam stream and an additional OpenCV window which shows a blue rectangle around a detected face.
Summary
This is just one example for using OpenCV in MeVisLab. You will find lots of other examples and tutorials online, we just wanted to show one possibility.