We can also do this for images with multiple faces.
image = cv2.imread("test_image5.jpg")
image = cv2.resize(image,(int(500),int(500)))
(h, w) = image.shape[:2]
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0))
net.setInput(blob)
detections = net.forward()
k = 0
# loop over the detections
for i in range(0, detections.shape[2]):
# extract the confidence (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 > min_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
if k==0:
newImage = np.array([[k, startY+2,endY-2, startX+2,endX-2]])
k += 1
else:
newImage = np.vstack((newImage, [[k, startY+2,endY-2, startX+2,endX-2]]))
k += 1
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)
for i in range(k):
face = image[newImage[i][1]:newImage[i][2], newImage[i][3]:newImage[i][4]]
name = 'face' + str(i) + '.jpg'
cv2.imwrite(name, face)