使用 OpenCV 進(jìn)行人臉檢測(cè)
使用 OpenCV 和 Python 檢測(cè)人臉的一種非常流行且簡(jiǎn)單的方法
步驟 01
我為此使用 Google Colab,首先,請(qǐng)確保你已安裝 OpenCV。你可以使用 pip 安裝它:
pip install opencv-python
步驟 02
請(qǐng)確保這些庫(kù)已經(jīng)安裝。
import cv2
pip install numpy
pip install matplotlib
步驟 03
在檢測(cè)人臉之前,我們必須使用 Google Colab 打開(kāi)網(wǎng)絡(luò)攝像頭。
from google.colab.patches import cv2_imshow
步驟 04
運(yùn)行這兩個(gè)代碼后,網(wǎng)絡(luò)攝像頭打開(kāi),你可以拍張照片。
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 級(jí)聯(lián)的人臉檢測(cè)是一種基于機(jī)器學(xué)習(xí)的方法,其中使用一組輸入數(shù)據(jù)訓(xùn)練級(jí)聯(lián)函數(shù)。OpenCV 已經(jīng)包含許多針對(duì)面部、眼睛、微笑等的預(yù)訓(xùn)練分類(lèi)器。今天我們將使用面部分類(lèi)器。你也可以嘗試使用其他分類(lèi)器。
要檢測(cè)圖像中的人臉:
步驟 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.")
對(duì)于每個(gè)人臉,繪制一個(gè)綠色矩形:
步驟 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 并打開(kāi) 。
結(jié)果:
photo_detected.jpg
原文標(biāo)題 : 使用 OpenCV 進(jìn)行人臉檢測(cè)

發(fā)表評(píng)論
請(qǐng)輸入評(píng)論內(nèi)容...
請(qǐng)輸入評(píng)論/評(píng)論長(zhǎng)度6~500個(gè)字
圖片新聞
最新活動(dòng)更多
-
8月5日立即報(bào)名>> 【在線會(huì)議】CAE優(yōu)化設(shè)計(jì):醫(yī)療器械設(shè)計(jì)的應(yīng)用案例與方案解析
-
8月14日立即報(bào)名>> 【在線研討會(huì)】解析安森美(onsemi)高精度與超低功耗CGM系統(tǒng)解決方案
-
精彩回顧立即查看>> 《2024智能制造產(chǎn)業(yè)高端化、智能化、綠色化發(fā)展藍(lán)皮書(shū)》
-
精彩回顧立即查看>> 7月30日- 8月1日 2025全數(shù)會(huì)工業(yè)芯片與傳感儀表展
-
精彩回顧立即查看>> 全數(shù)會(huì)2025(第六屆)機(jī)器人及智能工廠展
-
精彩回顧立即查看>> OFweek 2025 具身機(jī)器人動(dòng)力電池技術(shù)應(yīng)用大會(huì)
推薦專(zhuān)題
- 1 AI產(chǎn)業(yè)的新高度!英偉達(dá)成為全球首家市值破4萬(wàn)億美元的公司
- 2 傳魏建軍與賈躍亭合作,長(zhǎng)城汽車(chē)出海美國(guó)
- 3 一文讀懂:到底什么是 “具身智能” ?
- 4 黃仁勛:與雷軍長(zhǎng)期合作,共探AI智駕
- 5 具身智能泡沫爭(zhēng)議下,華映資本尋找「穿越周期者」
- 6 中國(guó)平安們欲靠AI守“陣地”
- 7 官宣:智元機(jī)器人借殼上市,A股人形機(jī)器人第一股!
- 8 華為讓渡“三界”銷(xiāo)售主導(dǎo)權(quán),智界高管:終于能全力奔跑了
- 9 借仿生手實(shí)現(xiàn)突圍,國(guó)產(chǎn)靈巧手破局“不可能三角”
- 10 DeepSeek R2加持,中國(guó)AI與芯片產(chǎn)業(yè)迎來(lái)新一輪協(xié)同進(jìn)化