Форум сайта python.su
Всем привет! Данный код выводит на экран видео с веб камеры, когда происходит захват лица, открываются еще два окна, в одном показывается вырезанное лицо, а во втором фото (фото находится в той же папке где и код). Как мне сравнить вырезанное лицо с веб камеры с имеющимся фото и если совпало то к примеру print('СОВПАДЕНИЕ').
Пожалуйста подскажите.
import cv2 import numpy as np faceCascade = cv2.CascadeClassifier('c:\opencv\sources\data\haarcascades_cuda\haarcascade_frontalface_default.xml') video_capture = cv2.VideoCapture(0) while True: ret, frame = video_capture.read() height,width,col=frame.shape gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE ) for (x, y, w, h) in faces: if len(faces)==1: face = frame[y:y+h,x:x+w] r = 100.0 / face.shape[1] dim = (100, int(face.shape[0] * r)) resized = cv2.resize(face, dim, interpolation = cv2.INTER_AREA) w_resized=resized.shape[0] h_resized=resized.shape[1] image = cv2.imread("2.bmp") cv2.imshow("Original image", image) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.imshow("", face) cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 3) frame[270:270+w_resized,540:540+h_resized] = resized cv2.imshow('Video', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break video_capture.release() cv2.destroyAllWindows()
Отредактировано IVAN222 (Сен. 20, 2017 17:55:51)
Офлайн
както так: https://habrahabr.ru/post/317798/
по моему как раз про ваш случай. А уж как это все прикрутить к вашему велосипеду - думайте.
[code python][/code]
Отредактировано PEHDOM (Сен. 20, 2017 14:53:53)
Офлайн
Спасибо, что подсказали где искать. Я в интернете много нашел про это. Но всех больше мне понравилось здесь. https://www.youtube.com/watch?v=4W5M-YaJtIA&t=340s
Здесь получается 3 кода.
1 код.
# Import OpenCV2 for image processing import cv2 # Start capturing video vid_cam = cv2.VideoCapture(0) # Detect object in video stream using Haarcascade Frontal Face face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # For each person, one face id face_id = 1 # Initialize sample face image count = 0 # Start looping while(True): # Capture video frame _, image_frame = vid_cam.read() # Convert frame to grayscale gray = cv2.cvtColor(image_frame, cv2.COLOR_BGR2GRAY) # Detect frames of different sizes, list of faces rectangles faces = face_detector.detectMultiScale(gray, 1.3, 5) # Loops for each faces for (x,y,w,h) in faces: # Crop the image frame into rectangle cv2.rectangle(image_frame, (x,y), (x+w,y+h), (255,0,0), 2) # Increment sample face image count += 1 # Save the captured image into the datasets folder cv2.imwrite("dataset/User." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w]) # Display the video frame, with bounded rectangle on the person's face cv2.imshow('frame', image_frame) # To stop taking video, press 'q' for at least 100ms if cv2.waitKey(100) & 0xFF == ord('q'): break # If image taken reach 100, stop taking video elif count>19: break # Stop video vid_cam.release() # Close all started windows cv2.destroyAllWindows()
# Import OpenCV2 for image processing # Import os for file path import cv2, os # Import numpy for matrix calculation import numpy as np # Import Python Image Library (PIL) from PIL import Image # Create Local Binary Patterns Histograms for face recognization recognizer = cv2.face.createLBPHFaceRecognizer() # Using prebuilt frontal face training model, for face detection detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml"); # Create method to get the images and label data def getImagesAndLabels(path): # Get all file path imagePaths = [os.path.join(path,f) for f in os.listdir(path)] # Initialize empty face sample faceSamples=[] # Initialize empty id ids = [] # Loop all the file path for imagePath in imagePaths: # Get the image and convert it to grayscale PIL_img = Image.open(imagePath).convert('L') # PIL image to numpy array img_numpy = np.array(PIL_img,'uint8') # Get the image id id = int(os.path.split(imagePath)[-1].split(".")[1]) # Get the face from the training images faces = detector.detectMultiScale(img_numpy) # Loop for each face, append to their respective ID for (x,y,w,h) in faces: # Add the image to face samples faceSamples.append(img_numpy[y:y+h,x:x+w]) # Add the ID to IDs ids.append(id) # Pass the face array and IDs array return faceSamples,ids # Get the faces and IDs faces,ids = getImagesAndLabels('dataset') # Train the model using the faces and IDs recognizer.train(faces, np.array(ids)) # Save the model into trainer.yml recognizer.save('trainer/trainer.yml')
# Import OpenCV2 for image processing import cv2 # Import numpy for matrices calculations import numpy as np # Create Local Binary Patterns Histograms for face recognization recognizer = cv2.face.createLBPHFaceRecognizer() # Load the trained mode recognizer.load('trainer/trainer.yml') # Load prebuilt model for Frontal Face cascadePath = "haarcascade_frontalface_default.xml" # Create classifier from prebuilt model faceCascade = cv2.CascadeClassifier(cascadePath); # Set the font style font = cv2.FONT_HERSHEY_SIMPLEX # Initialize and start the video frame capture cam = cv2.VideoCapture(0) # Loop while True: # Read the video frame ret, im =cam.read() # Convert the captured frame into grayscale gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) # Get all face from the video frame faces = faceCascade.detectMultiScale(gray, 1.2,5) # For each face in faces for(x,y,w,h) in faces: # Create rectangle around the face cv2.rectangle(im, (x-20,y-20), (x+w+20,y+h+20), (0,255,0), 4) # Recognize the face belongs to which ID Id = recognizer.predict(gray[y:y+h,x:x+w]) # Check the ID if exist if(Id == 1): Id = "Nazmi" #If not exist, then it is Unknown else: Id = "Unknown" # Put text describe who is in the picture cv2.rectangle(im, (x-22,y-90), (x+w+22, y-22), (0,255,0), -1) cv2.putText(im, str(Id), (x,y-40), font, 2, (255,255,255), 3) # Display the video frame with the bounded rectangle cv2.imshow('im',im) # If 'q' is pressed, close program if cv2.waitKey(10) & 0xFF == ord('q'): break # Stop the camera cam.release() # Close all windows cv2.destroyAllWindows()
Отредактировано IVAN222 (Сен. 25, 2017 16:14:07)
Офлайн
НУ вообще он должен идти в комплекте с Opencv
Но я так понимаю между Opencv2 и Opencv3 есть различия в том где какой модуль лежит. У вас видать инструкция для третьего , а сами используетет второй Opencv. Попробуйте так:
cv2.createLBPHFaceRecognizer()
[code python][/code]
Офлайн
cv2.createLBPHFaceRecognizer() так пробовал тоже самое.
У меня установлено:
python-3.5.3
opencv-3.3.0-vc14 (по моему это самая последняя версия)
через PIP установил:
Pillow-4.2.1-cp35-cp35m-win32.whl
PIL-2.0+dummy-py2.py3-none-any.whl
До этого было установлено opencv_python-3.2.0.6-cp35-cp35m-win32.whl Выдавало такую же ошибку,
посмотрев видео и под видео почитав ошибки, был совет для паитона3 и opencv-3 установить
opencv_contrib_python-3.3.0.10-cp35-cp35m-win32.whl
все равно получается такая же ошибка
Python 3.5.3 (v3.5.3:1880cb95a742, Jan 16 2017, 15:51:26) on win32
Type “copyright”, “credits” or “license()” for more information.
>>>
RESTART: C:\111111111111\Face-Recognition-master\training.py
Traceback (most recent call last):
File “C:\111111111111\Face-Recognition-master\training.py”, line 18, in <module>
recognizer = cv2.face.createLBPHFaceRecognizer()
AttributeError: module ‘cv2.face’ has no attribute ‘createLBPHFaceRecognizer’
>>>
Офлайн
тут на стековерфлов еще та советуют :
cv2.face.LBPHFaceRecognizer_create()
[code python][/code]
Офлайн
Немного сдвинулось дело. В коде 2 заменил строку
recognizer = cv2.face.createLBPHFaceRecognizer()
на эту
recognizer = cv2.face.LBPHFaceRecognizer_create()
код 2 стал рабочий. В паке haarcascade создался файл: trainer.yml
Теперь код 3, самый основной, опять вылезла ошибка:
>>>
RESTART: C:\111111111111\Face-Recognition-master\face_recognition.py
Traceback (most recent call last):
File “C:\111111111111\Face-Recognition-master\face_recognition.py”, line 17, in <module>
recognizer.load('trainer/trainer.yml')
AttributeError: ‘cv2.face_LBPHFaceRecognizer’ object has no attribute ‘load’
>>>
на этом коде строка 8
Отредактировано IVAN222 (Сен. 26, 2017 16:02:50)
Офлайн
Я это там и нашел на стековерфлов
Офлайн
Во 2 коде, создался файл trainer.yml и записался в папку trainer. крайняя строчка 2 кода:
recognizer.save('trainer/trainer.yml')
В 3 коде :
recognizer.load('trainer/trainer.yml')
обьект: cv2.face.LBPHFaceRecognizer_create не имеет атрибута load.
Значит во 2 коде cv2.face.LBPHFaceRecognizer_create запись прошла, а в 3 коде ему уже что то не хватает. ПОЧЕМУ…
Офлайн
Всем привет. Разобрался ПОЧЕМУ…? Потому, что в OPENCV 3 нет такого атрибута load , есть read.
http://docs.opencv.org/3.3.0/dd/d65/classcv_1_1face_1_1FaceRecognizer.html
Возникла следующая ошибка:
>>>
RESTART: C:\111111111111\Face-Recognition-master\facedetectionandrecoginiton.py
Traceback (most recent call last):
File “C:\111111111111\Face-Recognition-master\facedetectionandrecoginiton.py”, line 18, in <module>
Id, conf = recognizer.predict(gray)
cv2.error: C:\projects\opencv-python\opencv_contrib\modules\face\src\lbph_faces.cpp:396: error: (-5) This LBPH model is not computed yet. Did you call the train method? in function cv::face::LBPH::predict
>>>
Дальше надо разбираться. Так мелкими шагами и дойдем до конца.
Отредактировано IVAN222 (Окт. 1, 2017 19:06:06)
Офлайн