Home Backend Development Python Tutorial Face recognition in Python in AI

Face recognition in Python in AI

Apr 29, 2017 am 09:41 AM

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);
Copy after login

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)”
Copy after login

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
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1671
14
PHP Tutorial
1276
29
C# Tutorial
1256
24
Top 10 digital currency trading platforms: Top 10 safe and reliable digital currency exchanges Top 10 digital currency trading platforms: Top 10 safe and reliable digital currency exchanges Apr 30, 2025 pm 04:30 PM

The top 10 digital virtual currency trading platforms are: 1. Binance, 2. OKX, 3. Coinbase, 4. Kraken, 5. Huobi Global, 6. Bitfinex, 7. KuCoin, 8. Gemini, 9. Bitstamp, 10. Bittrex. These platforms all provide high security and a variety of trading options, suitable for different user needs.

Quantitative Exchange Ranking 2025 Top 10 Recommendations for Digital Currency Quantitative Trading APPs Quantitative Exchange Ranking 2025 Top 10 Recommendations for Digital Currency Quantitative Trading APPs Apr 30, 2025 pm 07:24 PM

The built-in quantization tools on the exchange include: 1. Binance: Provides Binance Futures quantitative module, low handling fees, and supports AI-assisted transactions. 2. OKX (Ouyi): Supports multi-account management and intelligent order routing, and provides institutional-level risk control. The independent quantitative strategy platforms include: 3. 3Commas: drag-and-drop strategy generator, suitable for multi-platform hedging arbitrage. 4. Quadency: Professional-level algorithm strategy library, supporting customized risk thresholds. 5. Pionex: Built-in 16 preset strategy, low transaction fee. Vertical domain tools include: 6. Cryptohopper: cloud-based quantitative platform, supporting 150 technical indicators. 7. Bitsgap:

Easeprotocol.com directly implements ISO 20022 message standard as a blockchain smart contract Easeprotocol.com directly implements ISO 20022 message standard as a blockchain smart contract Apr 30, 2025 pm 05:06 PM

This groundbreaking development will enable financial institutions to leverage the globally recognized ISO20022 standard to automate banking processes across different blockchain ecosystems. The Ease protocol is an enterprise-level blockchain platform designed to promote widespread adoption through easy-to-use methods. It announced today that it has successfully integrated the ISO20022 messaging standard and directly incorporated it into blockchain smart contracts. This development will enable financial institutions to easily automate banking processes in different blockchain ecosystems using the globally recognized ISO20022 standard, which is replacing the Swift messaging system. These features will be tried soon on "EaseTestnet". EaseProtocolArchitectDou

Is there a future for digital currency apps? Apple mobile digital currency trading platform app download TOP10 Is there a future for digital currency apps? Apple mobile digital currency trading platform app download TOP10 Apr 30, 2025 pm 07:00 PM

The prospects of digital currency apps are broad, which are specifically reflected in: 1. Technology innovation-driven function upgrades, improving user experience through the integration of DeFi and NFT and AI and big data applications; 2. Regulatory compliance trends, global framework improvements and stricter requirements for AML and KYC; 3. Function diversification and service expansion, integrating lending, financial management and other services and optimizing user experience; 4. User base and global expansion, and the user scale is expected to exceed 1 billion in 2025.

What are the three giants in the currency circle? Top 10 Recommended Virtual Currency Main Exchange APPs What are the three giants in the currency circle? Top 10 Recommended Virtual Currency Main Exchange APPs Apr 30, 2025 pm 06:27 PM

In the currency circle, the so-called Big Three usually refers to the three most influential and widely used cryptocurrencies. These cryptocurrencies have a significant role in the market and have performed well in terms of transaction volume and market capitalization. At the same time, the mainstream virtual currency exchange APP is also an important tool for investors and traders to conduct cryptocurrency trading. This article will introduce in detail the three giants in the currency circle and the top ten mainstream virtual currency exchange APPs recommended.

Failed crypto exchange FTX takes legal action against specific issuers in latest attempt Failed crypto exchange FTX takes legal action against specific issuers in latest attempt Apr 30, 2025 pm 05:24 PM

In its latest attempt, the resolved crypto exchange FTX has taken legal action to recover debts and pay back customers. In the latest efforts to recover debts and repay clients, the resolved crypto exchange FTX has filed legal action against specific issuers. FTX Trading and FTX Recovery Trust have filed lawsuits against certain token issuers who failed to fulfill their agreement to remit agreed coins to the exchange. Specifically, the restructuring team sued NFTStars Limited and Orosemi Inc. on Monday over compliance issues. FTX is suing the token issuer to recover the expired coins. FTX was once one of the most outstanding cryptocurrency trading platforms in the United States. The bank reported in November 2022 that its founder Sam

What are the reliable exchange platforms? The top ten digital currency exchanges What are the reliable exchange platforms? The top ten digital currency exchanges Apr 30, 2025 pm 04:15 PM

The top ten digital currency exchanges are: 1. Binance, 2. OKX, 3. Coinbase, 4. Kraken, 5. Huobi Global, 6. Bitfinex, 7. KuCoin, 8. Gemini, 9. Bitstamp, 10. Bittrex. These platforms all offer high security and a variety of trading options, suitable for different user needs.

Python vs. JavaScript: Which Language Should You Learn? Python vs. JavaScript: Which Language Should You Learn? May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles