Re: [Plugin Tiers][Sujet Principal] Face détection
Publié : 10 juil. 2018, 15:14
Si tu le permet je mettrai ton travail dans le plugin
Forum sur Jeedom
https://www.jeedom.com/forum/
Code : Tout sélectionner
curl -L https://raw.github.com/pageauc/opencv3-setup/master/setup.sh | bash
cd opencv3-setup/
#Et j'ai lancé la commande d'installation dans un screen
screen
./cv3-install-menu.sh
Code : Tout sélectionner
python
import cv2
cv2.__version__
Code : Tout sélectionner
apt-get install python-pip && sudo pip install picamera && sudo pip install rpio
Code : Tout sélectionner
sudo pip install "picamera[array]"
Code : Tout sélectionner
# import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 32
rawCapture = PiRGBArray(camera, size=(640, 480))
# allow the camera to warmup
time.sleep(0.1)
# capture frames from the camera
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
# grab the raw NumPy array representing the image, then initialize the timestamp
# and occupied/unoccupied text
image = frame.array
# show the frame
cv2.imshow("Frame", image)
key = cv2.waitKey(1) & 0xFF
# clear the stream in preparation for the next frame
rawCapture.truncate(0)
# if the `q` key was pressed, break from the loop
if key == ord("q"):
break
Code : Tout sélectionner
python test_video.py
Code : Tout sélectionner
sudo pip install dlib
sudo pip install face_recognition
sudo pip install imutils
Code : Tout sélectionner
raspistill -o 0001.jpg #incémentez de 1 entre chaques photos, prenez en au moins 5.
raspistill -o 0002.jpg
raspistill -o 0003.jpg
raspistill -o 0004.jpg
raspistill -o 0005.jpg
Code : Tout sélectionner
python encode_faces.py --dataset dataset --encodings encodings.pickle --detection-method hog
Code : Tout sélectionner
python pi_face_recognition.py --cascade haarcascade_frontalface_default.xml --encodings encodings.pickle
Code : Tout sélectionner
#!/usr/bin/env python3
import face_recognition
import argparse
import pickle
import cv2
import gi
import os
import time
import imutils
gi.require_version('Gst', '1.0')
gi.require_version('GstRtspServer', '1.0')
from gi.repository import Gst, GstRtspServer, GObject
class SensorFactory(GstRtspServer.RTSPMediaFactory):
def __init__(self, **properties):
super(SensorFactory, self).__init__(**properties)
self.cap = cv2.VideoCapture("rtsp://192.168.XXXXX")
#self.cap = cv2.VideoCapture("rtmp://192.168.YYYYY")
self.number_frames = 0
self.fps = 15
self.duration = 1 / self.fps * Gst.SECOND # duration of a frame in nanoseconds
self.launch_string = 'appsrc name=source is-live=true block=true format=GST_FORMAT_TIME ' \
'caps=video/x-raw,format=BGR,width=640,height=360,framerate={}/1 ' \
'! videoconvert ! video/x-raw,format=I420 ' \
'! x264enc speed-preset=ultrafast tune=zerolatency ' \
'! rtph264pay config-interval=1 name=pay0 pt=96'.format(self.fps)
def on_need_data(self, src, lenght):
if self.cap.isOpened():
ret, frame = self.cap.read()
rgb = imutils.resize(frame, width=750)
rgb = cv2.cvtColor(rgb,cv2.COLOR_BGR2RGB)
r = frame.shape[1] / float(rgb.shape[1])
boxes = face_recognition.face_locations(rgb,
model=args["detection_method"])
encodings = face_recognition.face_encodings(rgb, boxes)
names = []
for encoding in encodings:
matches = face_recognition.compare_faces(dataset["encodings"],
encoding)
name = "Unknown"
if True in matches:
matchedIdxs = [i for (i, b) in enumerate(matches) if b]
counts = {}
for i in matchedIdxs:
name = dataset["names"][i]
counts[name] = counts.get(name, 0) + 1
name = max(counts, key=counts.get)
names.append(name)
for ((top, right, bottom, left), name) in zip(boxes, names):
top = int(top * r)
right = int(right * r)
bottom = int(bottom * r)
left = int(left * r)
cv2.rectangle(frame, (left, top), (right, bottom),
(0, 255, 0), 2)
y = top - 15 if top - 15 > 15 else top + 15
cv2.putText(frame, name, (left, y), cv2.FONT_HERSHEY_SIMPLEX,
0.75, (0, 255, 0), 2)
indent = "dataset/" + name + "_" + time.strftime("%Y%m%d%H%M",time.gmtime()) + ".jpg"
exists = os.path.isfile(indent)
if not exists:
cv2.imwrite(indent, frame)
if args["display"] > 0:
out_frame = imutils.resize(frame, width=640, height=360)
data = out_frame.tostring()
buf = Gst.Buffer.new_allocate(None, len(data), None)
buf.fill(0, data)
buf.duration = self.duration
timestamp = self.number_frames * self.duration
buf.pts = buf.dts = int(timestamp)
buf.offset = timestamp
self.number_frames += 1
retval = src.emit('push-buffer', buf)
cv2.destroyAllWindows()
def do_create_element(self, url):
return Gst.parse_launch(self.launch_string)
def do_configure(self, rtsp_media):
self.number_frames = 0
appsrc = rtsp_media.get_element().get_child_by_name('source')
appsrc.connect('need-data', self.on_need_data)
class GstServer(GstRtspServer.RTSPServer):
def __init__(self, **properties):
super(GstServer, self).__init__(**properties)
self.factory = SensorFactory()
self.factory.set_shared(True)
self.get_mount_points().add_factory("/streamout", self.factory)
self.attach(None)
# construct the argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-y", "--display", type=int, default=0,
help="whether or not to display output frame to screen")
ap.add_argument("-d", "--detection-method", type=str, default="hog",
help="face detection model to use: either `hog` or `cnn`")
args = vars(ap.parse_args())
# grab the paths to the input images in our dataset
print("[INFO] loading encodings...")
dataset = pickle.loads(open("encodings.pickle", "rb").read())
GObject.threads_init()
Gst.init(None)
server = GstServer()
loop = GObject.MainLoop()
loop.run()
J'ai suivi votre tutoriel et tout fonctionne assez fluide. Je me demande s’il serait possible d’envoyer à jeedom les informations des différents visages détectés. Excusez le français, j'utilise le traducteur.tubezleb a écrit : ↑14 juil. 2018, 15:20Bon alors comme je l'ai dit cela reste une preuve ce concept.
1. Installation de OpenCV sur Raspberry PI3
Il y a des centaines de tuto sur comment installer OpenCV sur un RPI3. Heureusement je suis tombé sur un Github d'une personne qui propose un script d'instalation automatique.
https://github.com/pageauc/opencv3-setup
Donc dans le dossier /opt/ j'ai suivis les commandesSuiviez les étapes du menu en faisant 1,2,3 et 4Code : Tout sélectionner
curl -L https://raw.github.com/pageauc/opencv3-setup/master/setup.sh | bash cd opencv3-setup/ #Et j'ai lancé la commande d'installation dans un screen screen ./cv3-install-menu.sh
ATTENTION l'étape 3 (la compilation donc) va etre longue, cela a pris environ 4-5 heures sur mon RPi3.
une fois l'installation terminée vous pouvez voir si OpenCV est bien installé avec les conmnandes suivantes:
La sortie sera la suivante si tout est correct : '3.4.1'Code : Tout sélectionner
python import cv2 cv2.__version__
2. Test si OpenCV fonctionne bien avec la camera
J'ai installer d'abord des modules de python complémentaires:
Et aussi çaCode : Tout sélectionner
apt-get install python-pip && sudo pip install picamera && sudo pip install rpio
Copier le script suivant sur votre PI en tant que test_video.pyCode : Tout sélectionner
sudo pip install "picamera[array]"
Lancer le script avec la commande:Code : Tout sélectionner
# import the necessary packages from picamera.array import PiRGBArray from picamera import PiCamera import time import cv2 # initialize the camera and grab a reference to the raw camera capture camera = PiCamera() camera.resolution = (640, 480) camera.framerate = 32 rawCapture = PiRGBArray(camera, size=(640, 480)) # allow the camera to warmup time.sleep(0.1) # capture frames from the camera for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): # grab the raw NumPy array representing the image, then initialize the timestamp # and occupied/unoccupied text image = frame.array # show the frame cv2.imshow("Frame", image) key = cv2.waitKey(1) & 0xFF # clear the stream in preparation for the next frame rawCapture.truncate(0) # if the `q` key was pressed, break from the loop if key == ord("q"): break
, une fenêtre va s'afficher, affichant le flux vidéo de la caméra du PI.Code : Tout sélectionner
python test_video.py
ATTENTION: Si vous etes connecté en SSH vous ne verrez rien, a moins de faire une redirection X vers votre client SSH (Facile a faire avec mobaxterm), le mieux étant de brancher le PI directement sur un écran.
Miantenant que OpenCV est fonctionnel allons faire de la reconaissance faciale:
3. Reconaissance faciale
On commence par installer les modules python nécéssaires:
télécharger sur votre PI le zip suivant: https://drive.google.com/file/d/1SFNBhI ... ringharingCode : Tout sélectionner
sudo pip install dlib sudo pip install face_recognition sudo pip install imutils
Une fois décompressez, allez dans le dossier Dataset et créez un dossier avec votre nom, un fois dans ce dossier prenez des photos de vous avec la camera via la commande:Si vous souhaitez integrer une autre personne créez un autre dossier et faites la meme chose.Code : Tout sélectionner
raspistill -o 0001.jpg #incémentez de 1 entre chaques photos, prenez en au moins 5. raspistill -o 0002.jpg raspistill -o 0003.jpg raspistill -o 0004.jpg raspistill -o 0005.jpg
Une fois les photos prise, lancez le script suivant:
Ce script va compiler les images pour en faire un modèle pour la reconaissance faciale.Code : Tout sélectionner
python encode_faces.py --dataset dataset --encodings encodings.pickle --detection-method hog
Une fois ceci terminé lancez le script suivant pour lancer la reconaissance faciale:Une fenêtre va s'ouvrir affichant le flux vidéo, si la reconnaissance facile fonctionne correctement, vous devriez avoir un carré vert sur votre tête avec votre nom.Code : Tout sélectionner
python pi_face_recognition.py --cascade haarcascade_frontalface_default.xml --encodings encodings.pickle
Pour faire une action dans Jeedom lorsque votre visage est reconnu decommnetez la ligne 79 du script pi_face_recognition.py et mettez l'URL de l'action de Jeedom que vous souhaitez faire.
Donc voila jusqu’où je suis allé dans mes test pour le moment.
Sources:
https://github.com/pageauc/opencv3-setup
https://www.pyimagesearch.com/2018/06/2 ... cognition/
Bonjour,mika-nt28 a écrit : ↑06 sept. 2019, 11:25Bonjour a tous,
Je reviens vers se sujet car je vais reprendre le dev sur se plugin.
Je me suis mis au Python et sur openCV sur une autre projet de plugin et du coup j'ai pas mal avancé
Vue le travaille pour rendre fonctionnel le plugin sera payant.
Si vous souhaité qu'il reste dans cette etat et gratuit je cree un nouveau plugin utilisant openCV
Bonne idée.mika-nt28 a écrit :En faite je pense que je vais faire autrement
Le plugin est actuellement dispo en stable sur le market et il restera ainsi (il est voué a mourir car je ne le maintiendrai pas)
Je vas crée une nouveau qui ferra plutôt de la reconnaissance facial en plus de la detection de visage
Bonjour mika-nt28,mika-nt28 a écrit : ↑30 sept. 2019, 14:18En faite je pense que je vais faire autrement
Le plugin est actuellement dispo en stable sur le market et il restera ainsi (il est voué a mourir car je ne le maintiendrai pas)
Je vas crée une nouveau qui ferra plutôt de la reconnaissance facial en plus de la detection de visage