OpenCV is an open source library that can be used for image processing. It can also be used in Python, so it can also be used in machine learning. This time, I will try face recognition using this OpenCV.
This operating environment
Load the image, recognize the face in the image, and display the coordinates and size of the face. After that, the recognized face is displayed as a red square. OpenCV has several feature data files (cascade files) that can be used for face recognition. This time, we will use `haarcascade_frontalface_alt.xml``` as a data file that recognizes the face when facing the front. In addition, this time, it is recognized using the following image (
before.jpg `` `in the source code).
Reference source: https://www.pakutaso.com/assets_c/2016/03/SAYA151005380I9A8403-thumb-autox1600-21549.jpg
front_face.py
#coding: utf-8
import cv2
cascade_file = "haarcascade_frontalface_alt.xml"
image_file = "before.jpg "
img = cv2.imread(image_file)
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cascade = cv2.CascadeClassifier(cascade_file)
face_list = cascade.detectMultiScale(img_gray, minSize=(150, 150))
if len(face_list) == 0:
print("Fail recognise")
quit()
for (x, y, w, h) in face_list:
print("Face coordinates=", x, y, w, h)
color = (0, 0, 225)
pen_w = 8
cv2.rectangle(img, (x, y), (x+w, y+h), color, thickness = pen_w)
cv2.imwrite("after.jpg ", img)
When I ran it, I got the following error.
OpenCV Error: Assertion failed (!empty()) in detectMultiScale, file /home/travis/miniconda/conda-bld/conda_1486587069159/work/opencv-3.1.0/modules/objdetect/src/cascadedetect.cpp, line 1639
Traceback (most recent call last):
File "face_front.py", line 11, in <module>
face_list = cascade.detectMultiScale(img_gray, minSize=(150, 150))
cv2.error: /home/travis/miniconda/conda-bld/conda_1486587069159/work/opencv-3.1.0/modules/objdetect/src/cascadedetect.cpp:1639: error: (-215) !empty() in function detectMultiScale
--Cause
When I looked it up, it seems that the error is caused by the wrong path of the cascade file.
As a first aid, I was able to copy this cascade file to the directory containing the source code and use it.
The result of the execution is the following image.
From installing OpenCV 3.1 on Ubuntu16.04 LTS to face recognition test
Recommended Posts