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(
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() #關閉視窗
  • scaleFactor: Parameter specifying how much the image size is reduced at each image scale. Increasing it leads to faster detection with the risk of missing some objects, whereas a small value might sometimes be too thorough.
  • minNeighbors: Parameter specifying how many neighbors each candidate rectangle should have to retain it. Higher value results in less detection but with higher quality.
  • minSize: Minimum possible object size. Objects smaller than that are ignored.
  • maxSize: Maximum possible object size. Objects larger than that are ignored.
Image for post
Image for post


Written by

Machine Learning / Deep Learning / Python / Flutter

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