Python影像辨識筆記(一):使用Open CV辨識圖片及影片中的人臉

Image for post
Image for post
以電影海報為例

圖片人臉

安裝模組

pip install opencv-python

偵測人臉

import cv2# 載入分類器
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# 讀取圖片
img = cv2.imread('a.jpg')
# 轉成灰階圖片
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 偵測臉部faces = face_cascade.detectMultiScale(
gray,
scaleFactor=1.08,
minNeighbors=5,
minSize=(32, 32))
# 繪製人臉部份的方框
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
#(0, 255, 0)欄位可以變更方框顏色(Blue,Green,Red)# 顯示成果
cv2.namedWindow('img', cv2.WINDOW_NORMAL) #正常視窗大小
cv2.imshow('img', img) #秀出圖片
cv2.imwrite( "result.jpg", img ) #保存圖片
cv2.waitKey(0) #等待按下任一按鍵
cv2.destroyAllWindows() #關閉視窗
Image for post
Image for post
原始圖片

影片人臉

import cv2# 載入分類器
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# 從視訊盡頭擷取影片
cap = cv2.VideoCapture(0)
或者....# 使用現有影片
cap = cv2.VideoCapture('filename.mp4')
while True:
# Read the frame
_, img = cap.read()
# 轉成灰階
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 偵測臉部
faces = face_cascade.detectMultiScale(gray, 1.1, 4)
# 繪製人臉部份的方框
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2)
# 顯示成果cv2.namedWindow('img', cv2.WINDOW_NORMAL) #正常視窗大小
cv2.imshow('img', img) #秀出圖片
# Stop if escape key is pressed
k = cv2.waitKey(30) & 0xff
if k==27:
break

# Release the VideoCapture object
cap.release()
cv2.destroyAllWindows()

Written by

Machine Learning / Deep Learning / Python / Flutter cakeresume.com/yanwei-liu

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store