使用 OpenCV 進行人臉檢測
使用 OpenCV 和 Python 檢測人臉的一種非常流行且簡單的方法
步驟 01
我為此使用 Google Colab,首先,請確保你已安裝 OpenCV。你可以使用 pip 安裝它:
pip install opencv-python
步驟 02
請確保這些庫已經(jīng)安裝。
import cv2
pip install numpy
pip install matplotlib
步驟 03
在檢測人臉之前,我們必須使用 Google Colab 打開網(wǎng)絡攝像頭。
from google.colab.patches import cv2_imshow
步驟 04
運行這兩個代碼后,網(wǎng)絡攝像頭打開,你可以拍張照片。
from IPython.display import display, Javascript
from google.colab.output import eval_js
from base64 import b64decode
def take_photo(filename='photo.jpg', quality=0.8):
js = Javascript('''
async function takePhoto(quality) {
const div = document.createElement('div');
const capture = document.createElement('button');
capture.textContent = 'Capture';
div.a(chǎn)ppendChild(capture);
const video = document.createElement('video');
video.style.display = 'block';
const stream = await navigator.mediaDevices.getUserMedia({video: true});
document.body.a(chǎn)ppendChild(div);
div.a(chǎn)ppendChild(video);
video.srcObject = stream;
await video.play();
// Resize the output to fit the video element.
google.colab.output.setIframeHeight(document.documentElement.scrollHeight, true);
// Wait for Capture to be clicked.
await new Promise((resolve) => capture.onclick = resolve);
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
canvas.getContext('2d').drawImage(video, 0, 0);
stream.getVideoTracks()[0].stop();
div.remove();
return canvas.toDataURL('image/jpeg', quality);
}
''')
display(js)
data = eval_js('takePhoto({})'.format(quality))
binary = b64decode(data.split(',')[1])
with open(filename, 'wb') as f:
f.write(binary)
return filename
from IPython.display import Image
try:
filename = take_photo()
print('Saved to {}'.format(filename))
# Show the image which was just taken.
display(Image(filename))
except Exception as err:
# Errors will be thrown if the user does not have a webcam or if they do not
# grant the page permission to access it.
print(str(err))
照片保存為 photo.jpg。
photo.jpg
使用 Haar 級聯(lián)的人臉檢測是一種基于機器學習的方法,其中使用一組輸入數(shù)據(jù)訓練級聯(lián)函數(shù)。OpenCV 已經(jīng)包含許多針對面部、眼睛、微笑等的預訓練分類器。今天我們將使用面部分類器。你也可以嘗試使用其他分類器。
要檢測圖像中的人臉:
步驟 05
import cv2
img = cv2.imread('photo.jpg')
gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye.xml')
nose_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_nose.xml')
# detect all the faces in the image
faces = face_cascade.detectMultiScale(gray_img,1.1,4)
# print the number of faces detected
print(f"{len(faces)} faces detected in the image.")
對于每個人臉,繪制一個綠色矩形:
步驟 06
for x, y, width, height in faces:
cv2.rectangle(img, (x, y), (x + width, y + height), color=(0, 255, 0), thickness=2)
用矩形保存圖像:
步驟 07
# save the image with rectangles
cv2.imwrite("photo_detected.jpg", img)
轉(zhuǎn)到文件 photo_detected.jpg 并打開 。
結果:
photo_detected.jpg
原文標題 : 使用 OpenCV 進行人臉檢測

請輸入評論內(nèi)容...
請輸入評論/評論長度6~500個字
最新活動更多
推薦專題
- 1 UALink規(guī)范發(fā)布:挑戰(zhàn)英偉達AI統(tǒng)治的開始
- 2 北電數(shù)智主辦酒仙橋論壇,探索AI產(chǎn)業(yè)發(fā)展新路徑
- 3 降薪、加班、裁員三重暴擊,“AI四小龍”已折戟兩家
- 4 “AI寒武紀”爆發(fā)至今,五類新物種登上歷史舞臺
- 5 國產(chǎn)智駕迎戰(zhàn)特斯拉FSD,AI含量差幾何?
- 6 光計算迎來商業(yè)化突破,但落地仍需時間
- 7 東陽光:2024年扭虧、一季度凈利大增,液冷疊加具身智能打開成長空間
- 8 地平線自動駕駛方案解讀
- 9 封殺AI“照騙”,“淘寶們”終于不忍了?
- 10 優(yōu)必選:營收大增主靠小件,虧損繼續(xù)又逢關稅,能否乘機器人東風翻身?