With the shocking performance of alphago last year, AI has once again become the darling of technology companies. AI involves many fields, and face recognition in image recognition is one of the interesting branches. Baidu's BFR, Face++'s open platform, Hanwang, iFlytek, etc. all provide face recognition APIs. For experienced programmers, they can write a small piece of code to see how many people are in a picture. There are no tall and tall people. on, just for fun, and only requires 7 lines of code.
import cv2 face_patterns = cv2.CascadeClassifier('/usr/local/opt/opencv3/share/OpenCV/haarcascades/haarcascade_frontalface_default.xml') sample_image = cv2.imread('/Users/abel/201612.jpg') faces = face_patterns.detectMultiScale(sample_image,scaleFactor=1.1,minNeighbors=5,minSize=(100, 100)) for (x, y, w, h) in faces: cv2.rectangle(sample_image, (x, y), (x+w, y+h), (0, 255, 0), 2) cv2.imwrite('/Users/abel/201612_detected.png', sample_image);
Line 1 Introducing OpenCV
Open source is great, it allows us to broaden our horizons and does not have to reinvent the wheel. Instead of using PIL and combining it with a specific algorithm, OpenCV (http://opencv.org) is used directly. OpenCV is a cross-platform computer vision library released under the BSD license. It can run on Linux, Windows and Mac OS operating systems. It is lightweight and efficient. It is written in C/C++. It also provides Python, Ruby, MATLAB and other interfaces to implement Many general algorithms in image processing and computer vision.
Line 2 loads the classifier cv2.CascadeClassifier
CascadeClassifier is a cascade classifier used for face detection in Opencv. This class encapsulates the target detection mechanism, that is, the sliding window mechanism + Cascading classifiers. The data structure includes two main parts: Data and FeatureEvaluator. Data stores the classifier data loaded from the xml file obtained from training; while FeatureEvaluator is about the loading, storage and calculation of features. The training file used here is haarcascade frontalface default.xml provided by default in OpenCV. As for the specific principles of Haar and LBP, you can refer to the relevant documents of opencv. Simply, it can be understood as the feature data of the face.
Line 3 Load the target image imread
Face recognition systems are generally divided into: face image collection, face image preprocessing, face image feature extraction, and matching and recognition. For the sake of simplicity, read in the image,
Line 4 multi-scale detection detectMultiScale
Call the detectMultiScale function in CascadeClassifier for multi-scale detection, and the single-scale method will be called in multi-scale detection detectSingleScale. Parameter description:
scaleFactor is the scaling factor of the image
minNeighbors is the number of neighbors that should be retained for each cascade rectangle, which can be understood as how many faces are around a person
MinSize is the size of the detection window
These parameters can be adjusted for the picture, and the processing result returns a rectangular object list of faces.
Lines 5 and 6 draw a frame for each face
Loop through the list of rectangular objects of the face, obtain the coordinates, width and height of the face rectangle, and then draw it in the original picture To exit the rectangular frame, OpenCV's rectangle method is called, in which the color of the rectangular frame is adjustable.
Line 7 Save the test results
The mystery is not these 7 lines of code, but the related implementation in OpenCV. The Chinese website of OpenCV is also a good place to learn and experience.
Therefore, the 7 lines of code are just a gimmick, the real core is OpenCV. Then, there are some pitfalls when installing the OpenCV environment, so record them in particular.
Mac-based OpenCV environment
It is recommended to use Brew for installation. If brew is not installed, execute the following command first:
$/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)”
Then, specify the target warehouse $brew tap homebrew/science
Install OpenCV3 $brew install opencv3
The installation speed depends on the network. After installation, you need to bind the Python development environment. There are many ways:
1) Add environment variables and add the site-packages of opencv to the PYTHONPATH
2) Use ln soft connection to link cv2.so to the site-packages of the python environment
3 )Directly cp cv2.so to the site-packages directory of the python environment
More simply, execute the following command:
echo /usr/local/opt/opencv3/lib/python2.7/site-packages >> /usr/local/lib/python2.7/site-packages/opencv3.pth mkdir -p /Users/hecom/.local/lib/python2.7/site-packages echo 'import site; site.addsitedir("/usr/local/lib/python2.7/site-packages")' >> /Users/hecom/.local/lib/python2.7/site-packages/homebrew.pth
The above is the detailed content of Face recognition in Python in AI. For more information, please follow other related articles on the PHP Chinese website!

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 Chinese version
Chinese version, very easy to use

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software
