Unter Windows muss die Python Bibliothek für opencv mit:
pip install opencv-contrib-python
installiert werden.
Mit pip install opencv-python fehlt u.a. das cv2.face Modul
Die Fehlermeldung dazu lautet:
module ‚cv2.cv2‘ has no attribute ‚face‘
Danach klappt das Trainieren der Gesicht Erkennung und man kann die Familienmitglieder zu einem Fototermin einladen.
import cv2
from pathlib import Path
# Load pre-trained model 'haarcascade_frontalface.xml" for face recognition / classification
# von opencv GitHub Repository
faceCascade = cv2.CascadeClassifier('../haarcascade_frontalface.xml')
def saveImage(image, userName, userId, imgId):
# Create a folder with the name as userName
Path("dataset/{}".format(userName)).mkdir(parents=True, exist_ok=True)
# Save the images inside the previously created folder
cv2.imwrite("dataset/{}/{}_{}.jpg".format(userName, userId, imgId), image)
print("[INFO] Image {} has been saved in folder : {}".format(
imgId, userName))
# Create object for default camera 0
vc = cv2.VideoCapture(0)
print("Enter the id and name of the person")
userId = input()
userName = input()
count = 1
while True:
# Capture the frame/image
_, img = vc.read()
# Copy the original Image
originalImg = img.copy()
# Get the gray version of our image
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Get the coordinates of the location of the face in the picture
faces = faceCascade.detectMultiScale(gray_img,
scaleFactor=1.2,
minNeighbors=5,
minSize=(50, 50))
# Draw a rectangle at the location of the coordinates
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
coords = [x, y, w, h]
# Show the image
cv2.imshow("Identified Face", img)
# Wait for user keypress
key = cv2.waitKey(1) & 0xFF
# Check if the pressed key is 'k' or 'q'
if key == ord('s'):
# If count is less than 5 then save the image
if count <= 5:
roi_img = originalImg[coords[1] : coords[1] + coords[3], coords[0] : coords[0] + coords[2]]
saveImage(roi_img, userName, userId, count)
count += 1
else:
break
# If q is pressed break out of the loop
elif key == ord('q'):
break
print("[INFO] Dataset has been created for {}".format(userName))
# Stop the video camera
vc.release()
# Close all Windows
cv2.destroyAllWindows()
Quelle: https://github.com/packetcode/face-recognition-opencv
In dem YouTube Video zu dem Repo wird das auch noch genauer erklärt, es enthält aber einen kleinen Fehler, den ich hier korrigiert habe:
import cv2
import json
faceCascade = cv2.CascadeClassifier("../haarcascade_frontalface.xml")
# Call the trained model yml file to recognize faces
recognizer = cv2.face.LBPHFaceRecognizer_create()
# First train with train_model.ipynb
recognizer.read("../training.yml")
# Names corresponding to each id
# Die Reihenfolge der Namen vom Verzeichnis aus zu laden funktioniert nicht.
# Besser man speicher sich ein Array in ein JSON Dokument
# names.json: [ "Name1", "Name2", "Name3","..."]
with open("../names.json") as f:
names = json.load(f)
video_capture = cv2.VideoCapture(0)
while True:
_, img = video_capture.read()
gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray_image, scaleFactor=1.2, minNeighbors=5, minSize=(100, 100)
)
# Try to predict the face and get the id
# Then check if id == 1 or id == 2
# Accordingly add the names
for (x, y, w, h) in faces:
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
id, _ = recognizer.predict(gray_image[y : y + h, x : x + w])
if id:
cv2.putText(
img,
names[id-1],
(x, y - 4),
cv2.FONT_HERSHEY_SIMPLEX,
0.8,
(0, 255, 0),
1,
cv2.LINE_AA,
)
else:
cv2.putText(
img,
"Unknown",
(x, y - 4),
cv2.FONT_HERSHEY_SIMPLEX,
0.8,
(255, 0, 0),
1,
cv2.LINE_AA,
)
cv2.imshow("Recognize", img)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
video_capture.release()
cv2.destroyAllWindows()
Auf dem Raspberry Pi ist die letzte funktionierende armv71 Version übrigens die: 4.5.3.56. Ohne Versionsangabe schlägt die Installation nach langer Wartezeit fehl.
Die letzte Version findet man auch hier immer aktuell: opencv-contrib-python
pip3 install opencv-contrib-python==4.5.3.56
Und Last but not least:
Auf dem Raspi fehlten dann immer noch ein paar Dinge:
sudo apt install python3-h5py # (https://docs.h5py.org/en/stable/)
sudo apt install libatlas-base-dev # (https://packages.debian.org/de/sid/libatlas-base-dev)
pip install -U numpy # (Aktuelle Version von numpy)