用Python和OpenCV人臉檢測神經網絡檢測人臉

用Python和OpenCV人臉檢測神經網絡檢測人臉

用Python和OpenCV人臉檢測神經網絡檢測人臉

現在,我們都知道人工智能正在變得越來越真實,它日益填補人類和機器之間的能力差距。它不再是一個花哨的詞。多年來,它在許多領域取得了許多進步,其中一個領域是計算機視覺領域。

談到計算機視覺,它的目標是訓練機器像人類一樣觀察和識別世界。並且還收集足夠多的知識以執行圖像和視頻識別,圖像分析和分類,媒體娛樂,自然語言處理等。

卷積神經網絡

隨著時間的推移,計算機視覺的進步已經逐步實現和完善,主要是通過一種特定的算法 - 卷積神經網絡(CNNs或ConvNets),這是一種特殊類型的前饋網絡,主要用於分析視覺圖像。卷積神經網絡與普通神經網絡非常相似,由可學習權重和偏差的神經元組成。

卷積神經網絡由於其獨特的處理過程而優於其他深層神經網絡體系結構。ConvNets不是一次查看一個像素,而是將多個像素分組,以便理解時間模式。換句話說,ConvNets可以“看到”一組像素組成一條線或一條曲線。由於深度神經網絡的深層性質,在下一深度中,它們看到的不是一組像素,而是一組形成某些形狀的直線和曲線組。依此類推,直到他們形成完整的畫面。

遷移學習

然而,CNNs需要大量的數據集和大量的計算時間來訓練。有些甚至可能需要2-3周才能在多個GPU上運行。如果你想了解CNNs,你需要學習很多東西,從基本的東西,從最基本的東西開始,比如內核、池層等等。但是現在, 您可以直接使用許多開源項目來實現這項技術。

這實際上是因為稱為遷移學習的技術。遷移學習是一種非常實用和強大的技術,它利用訓練過的模型而不是從頭開始訓練網絡。遷移學習利用不同數據集上的訓練模型,並使其適應我們試圖解決的問題。

為了構建我們的應用程序,我們將遵循遷移學習技術並使用經過訓練的模型,該模型使用Caffe框架進行訓練,這是一個深入學習框架,以表達,速度和模塊化為基礎。Caffe附帶了一個存儲庫,供研究人員和機器學習從業者用來共享他們訓練過的模型。該庫稱為Model Zoo。

啟動程序

在我們的應用程序中,我們將使用以下庫:

  1. OpenCV,它支持許多與計算機視覺和機器學習相關的算法,更不用說它是建立在深度神經網絡中的,我們將在應用程序中使用。
  2. Numpy,這是一個用於python科學計算的軟件包。
  3. OS,提供使用操作系統相關功能的可移植方法

因此,要安裝它們,可以在“命令提示符”窗口中運行以下命令。pip install opencv-python安裝OpenCV,pip install numpy安裝Numpy,不需要專門安裝OS庫,因為Python中已經附帶有了,我們只是需要導入即可。

構建應用程序

首先,讓我們創建一個名為faceDetection.py的文件並導入我們的庫。

#import libraries
import os
import cv2
import numpy

現在,我們將獲得工作目錄的絕對路徑,我們將所有圖像放置在這裡,

#import libraries
import os
import cv2
import numpy
#get the absolute path of the working directory
dir_path = os.path.dirname(os.path.realpath(__file__))

現在,我們將創建一個名為“Output”的文件夾,以放置我們的最終圖像。

#import libraries
import os
import cv2
import numpy
#get the absolute path of the working directory
dir_path = os.path.dirname(os.path.realpath(__file__))
#create the Output folder if it doesn't already exist
if not os.path.exists('Output'):
os.makedirs('Output')

之後,我們將從當前工作目錄加載我們預先訓練的模型和proto.txt文件。

#import libraries
import os
import cv2
import numpy
#get the absolute path of the working directory
dir_path = os.path.dirname(os.path.realpath(__file__))
#create the Output folder if it doesn't already exist
if not os.path.exists('Output'):
os.makedirs('Output')
#Reads the network model stored in Caffe framework's format.
model = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'weights.caffemodel')

然後,我們將遍歷當前文件夾中可用的文件,以檢查是否存在擴展名為.png,.jpg和.jpeg的文件。

#import libraries
import os
import cv2
import numpy
#get the absolute path of the working directory
dir_path = os.path.dirname(os.path.realpath(__file__))
#create the Output folder if it doesn't already exist
if not os.path.exists('Output'):
os.makedirs('Output')
#Reads the network model stored in Caffe framework's format.
model = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'weights.caffemodel')
for file in os.listdir(dir_path):
#split the file name and the extension into two variales
filename, file_extension = os.path.splitext(file)
#check if the file extension is .png,.jpeg or .jpg
if (file_extension in ['.png','.jpg','.jpeg']):

如果找到具有上述擴展名的圖像,我們將使用OpenCV讀取圖像,並通過訪問image.shape獲取它的高度和寬度,然後取前兩個元素來繪製矩形。

#import libraries
import os
import cv2
import numpy
#get the absolute path of the working directory
dir_path = os.path.dirname(os.path.realpath(__file__))
#create the Output folder if it doesn't already exist
if not os.path.exists('Output'):
os.makedirs('Output')
#Reads the network model stored in Caffe framework's format.
model = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'weights.caffemodel')
for file in os.listdir(dir_path):
#split the file name and the extension into two variales
filename, file_extension = os.path.splitext(file)
#check if the file extension is .png,.jpeg or .jpg
if (file_extension in ['.png','.jpg','.jpeg']):
#read the image using cv2
image = cv2.imread(file)
#accessing the image.shape tuple and taking the elements
(h, w) = image.shape[:2]

然後,我們將cv2.dnn.blobFromImage函數通過將圖像作為輸入來獲取我們的blob 。使用cv2.dnn.blobFromImage函數我們將圖像調整為300x300維度,1.0是比例因子,這裡我們使用默認值,因此沒有縮放,之後是卷積神經網絡預測的空間大小,最後的值是元組中的平均減法值,它們是RGB均值,最後,函數返回一個“blob”,它是調整大小,平均減法和標準化後的輸入圖像。

之後,我們將blob輸入模型並使用model.foreward函數獲取檢測。

#import libraries
import os
import cv2
import numpy
#get the absolute path of the working directory
dir_path = os.path.dirname(os.path.realpath(__file__))
#create the Output folder if it doesn't already exist
if not os.path.exists('Output'):
os.makedirs('Output')
#Reads the network model stored in Caffe framework's format.
model = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'weights.caffemodel')
for file in os.listdir(dir_path):
#split the file name and the extension into two variales
filename, file_extension = os.path.splitext(file)
#check if the file extension is .png,.jpeg or .jpg
if (file_extension in ['.png','.jpg','.jpeg']):
#read the image using cv2
image = cv2.imread(file)
#accessing the image.shape tuple and taking the elements
(h, w) = image.shape[:2]
#get our blob which is our input image
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))
#input the blob into the model and get back the detections
model.setInput(blob)
detections = model.forward()
用Python和OpenCV人臉檢測神經網絡檢測人臉

然後,我們將遍歷所有檢測到的所有面,並提取它們的起點和終點。我們將提取置信度並將其與置信度閾值進行比較,這樣我們就可以過濾掉微弱的檢測。如果算法對人臉檢測的置信度超過16.5%,我們將在其上顯示一個綠色矩形。

#import libraries
import os
import cv2
import numpy
#get the absolute path of the working directory
dir_path = os.path.dirname(os.path.realpath(__file__))
#create the Output folder if it doesn't already exist
if not os.path.exists('Output'):
os.makedirs('Output')
#Reads the network model stored in Caffe framework's format.
model = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'weights.caffemodel')
for file in os.listdir(dir_path):
#split the file name and the extension into two variales
filename, file_extension = os.path.splitext(file)
#check if the file extension is .png,.jpeg or .jpg
if (file_extension in ['.png','.jpg','.jpeg']):
#read the image using cv2
image = cv2.imread(file)
#accessing the image.shape tuple and taking the elements
(h, w) = image.shape[:2]
#get our blob which is our input image
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))
#input the blob into the model and get back the detections
model.setInput(blob)
detections = model.forward()
#Iterate over all of the faces detected and extract their start and end points
count = 0
for i in range(0, detections.shape[2]):
box = detections[0, 0, i, 3:7] * numpy.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
confidence = detections[0, 0, i, 2]
#if the algorithm is more than 16.5% confident that the detection is a face, show a rectangle around it
if (confidence > 0.165):
cv2.rectangle(image, (startX, startY), (endX, endY), (0, 255, 0), 2)
count = count + 1

最後,我們將輸出圖像保存在我們創建的Output文件夾中,並輸出一條成功消息,讓用戶知道它已完成。

#import libraries
import os
import cv2
import numpy
#get the absolute path of the working directory
dir_path = os.path.dirname(os.path.realpath(__file__))
#create the Output folder if it doesn't already exist
if not os.path.exists('Output'):
os.makedirs('Output')
#Reads the network model stored in Caffe framework's format.
model = cv2.dnn.readNetFromCaffe('deploy.prototxt', 'weights.caffemodel')
for file in os.listdir(dir_path):
#split the file name and the extension into two variales
filename, file_extension = os.path.splitext(file)
#check if the file extension is .png,.jpeg or .jpg
if (file_extension in ['.png','.jpg','.jpeg']):
#read the image using cv2
image = cv2.imread(file)
#accessing the image.shape tuple and taking the elements
(h, w) = image.shape[:2]
#get our blob which is our input image
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))
#input the blob into the model and get back the detections
model.setInput(blob)
detections = model.forward()
#Iterate over all of the faces detected and extract their start and end points
count = 0
for i in range(0, detections.shape[2]):
box = detections[0, 0, i, 3:7] * numpy.array([w, h, w, h])
(startX, startY, endX, endY) = box.astype("int")
confidence = detections[0, 0, i, 2]
#if the algorithm is more than 16.5% confident that the detection is a face, show a rectangle around it
if (confidence > 0.165):
cv2.rectangle(image, (startX, startY), (endX, endY), (0, 255, 0), 2)
count = count + 1
#save the modified image to the Output folder
cv2.imwrite('Output/' + file, image)
#print out a success message
print("Face detection complete for image "+ file + " ("+ str(count) +") faces found!")
用Python和OpenCV人臉檢測神經網絡檢測人臉

我希望你喜歡這個結果!現在,您可以隨時使用代碼來了解每個函數的作用。如果您想閱讀並獲取更多信息,OpenCV提供了很好的文檔和教程。

結論

在這篇文章中,我們講解了:

  1. 卷積神經網絡的概念以及我們如何通過遷移學習和預訓練模型節省大量時間和精力。
  2. 以及我們如何使用預先訓練好的Caffe模型來實現我們的應用程序。
  3. 安裝所需的庫並設置環境。

最後,我們實現了一個可以使用圖像進行檢測的python程序。

相關推薦

推薦中...