Изменение размера моей камеры выводит ошибку, когда используется для прогнозирования по модели - PullRequest
0 голосов
/ 09 октября 2019

Итак, я сделал модель, чтобы узнавать некоторых людей. Я использую свою веб-камеру для прогнозирования по модели, но она выдает ошибку. Ошибка переходит на roi_color, где я изменяю размер камеры, чтобы она соответствовала моей модели.

Так что я недавно решил проблему, когда я не знал, как изменить размер камеры и избавился от ошибки, но теперь эта ошибка приходит, и японятия не имею, как ее решить, плюс у меня нет большого опыта в распознавании лиц, и с такими ошибками действительно сложно что-то узнать ...

Любая помощь приветствуется, спасибо!

import numpy as np
import cv2
import random as rd
from pathlib import Path
import string
from keras.models import model_from_json


def Recog_face(x, y, roi_color, frame, recognizer_face):
    predictions = recognizer_face.predict(roi_color)
    color = (255, 255, 255) 
    stroke = 2   
    font = cv2.FONT_HERSHEY_SIMPLEX 
    return cv2.putText(frame, predictions, (x,y), font, 1, color, stroke, cv2.LINE_AA)

def Detect_face(x, y, frame):
    color = (255, 0, 0)
    stroke = 1 
    end_cord_x = x + w 
    end_cord_y = y + h 
    return cv2.rectangle(frame, (x, y), (end_cord_x, end_cord_y), color, stroke) 

face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')




recognizer_face = model_from_json(open("face_rec.json", "r").read()) 


recognizer_face.load_weights('face_rec.h5')



cap = cv2.VideoCapture(0)


while True:

    ret, frame = cap.read() 
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.5, 
                                         minNeighbors=5)

    for (x, y, w, h) in faces: 

        roi_gray = gray[y:y+h, x:x+w] 
        roi_color = frame[y:y+h, x:x+w][None]
        roi_color = cv2.resize(roi_color, (64, 64))

        Detect_face(x, y, frame)

        # Face recognizer
        Recog_face(x, y, roi_color, frame, recognizer_face)





    cv2.imshow('frame', frame)
    if cv2.waitKey(20) & 0xFF == ord('q'):
        break 

cap.release()
cv2.destroyAllWindows()
from keras.models import Sequential
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense

classifier = Sequential()

# Convolution
classifier.add(Convolution2D(32, 3, 3, input_shape=(64, 64, 3), activation='relu')) 
# Maxpooling To reduce the number of nodes will get in flattening step
# Pooling
classifier.add(MaxPooling2D(pool_size = (2, 2))) 
# adding second Convolution layer
classifier.add(Convolution2D(32, 3, 3, activation='relu'))
classifier.add(MaxPooling2D(pool_size = (2, 2))) 
# Flatten
classifier.add(Flatten())
# Full connection
classifier.add(Dense(output_dim = 128, activation = 'relu')) # 128 hidden nodes in the hidden layer
classifier.add(Dense(output_dim = 5, activation = 'softmax')) # softmax function cause multiple outcome 
# Compiling the CNN
classifier.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])
print(classifier.summary()) 



from keras.preprocessing.image import ImageDataGenerator


train_datagen = ImageDataGenerator(rescale=1./255, 
                                  shear_range=0.2, 
                                  zoom_range=0.2,
                                  horizontal_flip=True)

test_datagen = ImageDataGenerator(rescale=1./255)


training_set = train_datagen.flow_from_directory('images/Training_set',
                                                target_size=(64, 64), 
                                                batch_size=32,
                                                color_mode='rgb',
                                                class_mode='categorical') 

test_set = test_datagen.flow_from_directory('images/Test_set',
                                            target_size=(64, 64),
                                            batch_size=32,
                                            color_mode='rgb',
                                            class_mode='categorical') 
classifier.fit_generator(training_set,
                        steps_per_epoch=380,
                        epochs=2,
                        validation_data= test_set,
                        validation_steps=127)


fer_json = classifier.to_json()
with open("face_rec.json", "w") as json_file:
    json_file.write(fer_json)
classifier.save_weights("face_rec.h5")
...