天天看點

python人臉照片分類_python實作圖像,視訊人臉識别(opencv版)

圖檔人臉識别

import cv2

filepath = "img/xingye-1.png"

img = cv2.imread(filepath) # 讀取圖檔

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # 轉換灰色

# OpenCV人臉識别分類器

classifier = cv2.CascadeClassifier(

"C:\Python36\Lib\site-packages\opencv-master\data\haarcascades\haarcascade_frontalface_default.xml"

)

color = (0, 255, 0) # 定義繪制顔色

# 調用識别人臉

faceRects = classifier.detectMultiScale(

gray, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))

if len(faceRects): # 大于0則檢測到人臉

for faceRect in faceRects: # 單獨框出每一張人臉

x, y, w, h = faceRect

# 框出人臉

cv2.rectangle(img, (x, y), (x + h, y + w), color, 2)

# 左眼

cv2.circle(img, (x + w // 4, y + h // 4 + 30), min(w // 8, h // 8),

color)

#右眼

cv2.circle(img, (x + 3 * w // 4, y + h // 4 + 30), min(w // 8, h // 8),

color)

#嘴巴

cv2.rectangle(img, (x + 3 * w // 8, y + 3 * h // 4),

(x + 5 * w // 8, y + 7 * h // 8), color)

cv2.imshow("image", img) # 顯示圖像

c = cv2.waitKey(10)

cv2.waitKey(0)

cv2.destroyAllWindows()

視訊人臉識别

# -*- coding:utf-8 -*-

# OpenCV版本的視訊檢測

import cv2

# 圖檔識别方法封裝

def discern(img):

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

cap = cv2.CascadeClassifier(

"C:\Python36\Lib\site-packages\opencv-master\data\haarcascades\haarcascade_frontalface_default.xml"

)

faceRects = cap.detectMultiScale(

gray, scaleFactor=1.2, minNeighbors=3, minSize=(50, 50))

if len(faceRects):

for faceRect in faceRects:

x, y, w, h = faceRect

cv2.rectangle(img, (x, y), (x + h, y + w), (0, 255, 0), 2) # 框出人臉

cv2.imshow("Image", img)

# 擷取攝像頭0表示第一個攝像頭

cap = cv2.VideoCapture(0)

while (1): # 逐幀顯示

ret, img = cap.read()

# cv2.imshow("Image", img)

discern(img)

if cv2.waitKey(1) & 0xFF == ord('q'):

break

cap.release() # 釋放攝像頭

cv2.destroyAllWindows() # 釋放視窗資源

以上就是python實作圖像,視訊人臉識别(opencv版)的詳細内容,更多關于python 人臉識别的資料請關注随便開發網其它相關文章!