1. 程式人生 > >opencv+deep-learning實現人臉識別

opencv+deep-learning實現人臉識別

早在2017年8月,OpenCV 3.3正式釋出,帶來了高度改進的“深度神經網路”(dnn)模組。

該模組支援許多深度學習框架,包括Caffe,TensorFlow和Torch / PyTorch。

dnn模組的主要貢獻者Aleksandr Rybnikov已經投入了大量的工作來使這個模組成為可能。

 自從OpenCV 3.3釋出以來,有一些深度學習的OpenCV教程。然後在opencv中包含了深度學習高準確度的人臉識別器,可能不時廣泛的為人所熟知,但是效果卻好的驚人。這麼好玩,不要顧著激動,趕緊玩起來啊。

當使用OpenCV的深度神經網路模組和Caffe模型時,需要兩組檔案:

     定義模型體系結構的.prototxt

檔案(即層本身)
     .caffemodel檔案,包含實際圖層的權重

當使用使用Caffe訓練的模型進行深度學習時,這兩個檔案都是必需的。

但是,只能在GitHub倉庫中找到原型檔案。

權重檔案不包含在OpenCV示例目錄中,需要更多挖掘才能找到它們...

OpenCV的深度學習面部檢測器基於具有ResNet基礎網路的單次檢測(SSD)框架(與已有的其他OpenCV SSD不同,它通常使用MobileNet作為基礎網路)。


應用opencv人臉檢測器檢測單張影象


detect_faces.py

 

# import the necessary packages
import numpy as np
import argparse
import cv2

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True,
	help="path to input image")
ap.add_argument("-p", "--prototxt", required=True,
	help="path to Caffe 'deploy' prototxt file")
ap.add_argument("-m", "--model", required=True,
	help="path to Caffe pre-trained model")
ap.add_argument("-c", "--confidence", type=float, default=0.5,
	help="minimum probability to filter weak detections")
args = vars(ap.parse_args())
# load our serialized model from disk
print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])

# load the input image and construct an input blob for the image
# by resizing to a fixed 300x300 pixels and then normalizing it
image = cv2.imread(args["image"])
(h, w) = image.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0,
	(300, 300), (104.0, 177.0, 123.0))
# pass the blob through the network and obtain the detections and
# predictions
print("[INFO] computing object detections...")
net.setInput(blob)
detections = net.forward()
# loop over the detections
for i in range(0, detections.shape[2]):
	# extract the confidence (i.e., probability) associated with the
	# prediction
	confidence = detections[0, 0, i, 2]

	# filter out weak detections by ensuring the `confidence` is
	# greater than the minimum confidence
	if confidence > args["confidence"]:
		# compute the (x, y)-coordinates of the bounding box for the
		# object
		box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
		(startX, startY, endX, endY) = box.astype("int")
 
		# draw the bounding box of the face along with the associated
		# probability
		text = "{:.2f}%".format(confidence * 100)
		y = startY - 10 if startY - 10 > 10 else startY + 10
		cv2.rectangle(image, (startX, startY), (endX, endY),
			(0, 0, 255), 2)
		cv2.putText(image, text, (startX, y),
			cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)

# show the output image
cv2.imshow("Output", image)
cv2.waitKey(0)

run

$ python detect_faces.py --image rooster.jpg --prototxt deploy.prototxt.txt \
	--model res10_300x300_ssd_iter_140000.caffemodel

輸出帶有檢測框和置信度的人臉檢測結果,可以檢測多張人臉。OpenCV的Haar級聯因缺少“直接”角度的面孔而效果不佳,但通過使用OpenCV的深度學習面部探測器,我們能夠檢測到我的臉部。


人臉檢測器檢測視訊或者攝像頭中的資料流


detect_faces_video.py

# import the necessary packages
from imutils.video import VideoStream
import numpy as np
import argparse
import imutils
import time
import cv2

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--prototxt", required=True,
	help="path to Caffe 'deploy' prototxt file")
ap.add_argument("-m", "--model", required=True,
	help="path to Caffe pre-trained model")
ap.add_argument("-c", "--confidence", type=float, default=0.5,
	help="minimum probability to filter weak detections")
args = vars(ap.parse_args())
# load our serialized model from disk
print("[INFO] loading model...")
net = cv2.dnn.readNetFromCaffe(args["prototxt"], args["model"])

# initialize the video stream and allow the camera sensor to warm up
print("[INFO] starting video stream...")
vs = VideoStream(src=0).start()
time.sleep(2.0)
# loop over the frames from the video stream
while True:
	# grab the frame from the threaded video stream and resize it
	# to have a maximum width of 400 pixels
	frame = vs.read()
	frame = imutils.resize(frame, width=400)
 
	# grab the frame dimensions and convert it to a blob
	(h, w) = frame.shape[:2]
	blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0,
		(300, 300), (104.0, 177.0, 123.0))
 
	# pass the blob through the network and obtain the detections and
	# predictions
	net.setInput(blob)
	detections = net.forward()
	# loop over the detections
	for i in range(0, detections.shape[2]):
		# extract the confidence (i.e., probability) associated with the
		# prediction
		confidence = detections[0, 0, i, 2]

		# filter out weak detections by ensuring the `confidence` is
		# greater than the minimum confidence
		if confidence < args["confidence"]:
			continue

		# compute the (x, y)-coordinates of the bounding box for the
		# object
		box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
		(startX, startY, endX, endY) = box.astype("int")
 
		# draw the bounding box of the face along with the associated
		# probability
		text = "{:.2f}%".format(confidence * 100)
		y = startY - 10 if startY - 10 > 10 else startY + 10
		cv2.rectangle(frame, (startX, startY), (endX, endY),
			(0, 0, 255), 2)
		cv2.putText(frame, text, (startX, y),
			cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
	# show the output frame
	cv2.imshow("Frame", frame)
	key = cv2.waitKey(1) & 0xFF
 
	# if the `q` key was pressed, break from the loop
	if key == ord("q"):
		break

# do a bit of cleanup
cv2.destroyAllWindows()
vs.stop()

這裡默認了已經具備python和DL的基礎,程式碼層面直接讀懂應該沒有問題的,就不費時說明了。

run

$ python detect_faces_video.py --prototxt deploy.prototxt.txt \
	--model res10_300x300_ssd_iter_140000.caffemodel

總結

 這裡給出一個一個比較友好的opencv人臉檢測器的例項。

OpenCV庫 中帶有更精確的人臉檢測器(與OpenCV的Haar級聯相比)。

更精確的OpenCV人臉檢測器是基於深度學習的,特別是利用ResNet檢測器(SSD)框架和ResNet作為基礎網路。

受益於Aleksandr Rybnikov和OpenCV的dnn模組的其他貢獻者。