DanZX3 commited on
Commit
ab8b210
1 Parent(s): 25d8f52

actualizacion de modelo y diccionario

Browse files
Files changed (3) hide show
  1. app.py +62 -52
  2. face_classifier_model.h5 +1 -1
  3. vgg_face_model.h5 +0 -3
app.py CHANGED
@@ -11,88 +11,98 @@ import matplotlib.pyplot as plt
11
  from tensorflow.keras.models import Sequential
12
  from tensorflow.keras.layers import Dense, BatchNormalization, Activation, Dropout
13
 
14
- # Cargar el modelo preentrenado y otros recursos necesarios
15
  model_path = './face_classifier_model.h5'
16
- # Cargar el modelo VGG-Face
17
  vgg_face_path = './vgg_face_model.h5'
 
 
18
  vgg_face = load_model(vgg_face_path)
19
 
 
20
  dnnFaceDetector = dlib.cnn_face_detection_model_v1("mmod_human_face_detector.dat")
21
 
22
- # Cargar el modelo sin compilar
23
  classifier_model = tf.keras.models.load_model(model_path, compile=False)
24
 
25
- # Compilar el modelo manualmente con los mismos par谩metros que se us贸 en Colab
26
  classifier_model.compile(loss=tf.keras.losses.SparseCategoricalCrossentropy(),
27
  optimizer='nadam',
28
  metrics=['accuracy'])
29
 
30
- person_rep={0: 'DenzelWashington',
31
- 1: 'AngelinaJolie',
32
- 2: 'KateWinslet',
33
- 3: 'HughJackman',
34
- 4: 'ScarlettJohansson',
35
- 5: 'JenniferLawrence',
36
- 6: 'NicoleKidman',
37
- 7: 'SandraBullock',
38
- 8: 'LeonardoDiCaprio',
39
- 9: 'MeganFox',
40
- 10: 'WillSmith',
41
- 11: 'TomCruise',
42
- 12: 'BradPitt',
43
- 13: 'NataliePortman',
44
- 14: 'TomHanks',
45
- 15: 'JohnnyDepp',
46
- 16: 'RobertDowneyJr'}
47
-
 
 
48
  def predict_image(image_path):
49
- img = load_img(image_path, target_size=(224, 224))
50
- img = img_to_array(img)
51
- img = np.expand_dims(img, axis=0)
52
- img = preprocess_input(img)
53
 
54
- img_encode = vgg_face(img)
55
- predictions = classifier_model.predict(img_encode)
56
  return predictions
57
 
58
- # Interfaz de Streamlit
59
  st.title("Reconocimiento Facial")
60
  st.write("Sube una imagen y el modelo intentar谩 identificar el rostro.")
61
 
 
62
  uploaded_file = st.file_uploader("Elige una imagen...", type="jpg")
63
 
 
64
  if uploaded_file is not None:
65
- file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8)
66
- img = cv2.imdecode(file_bytes, 1)
67
 
68
- gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
69
- rects = dnnFaceDetector(gray, 1)
70
 
 
71
  for (i, rect) in enumerate(rects):
72
- left = rect.rect.left() # x1
73
- top = rect.rect.top() # y1
74
- right = rect.rect.right() # x2
75
- bottom = rect.rect.bottom() # y2
76
  width = right - left
77
  height = bottom - top
78
- img_crop = img[top:top + height, left:left + width]
79
- cv2.imwrite('crop_img.jpg', img_crop)
80
-
81
- crop_img = load_img('crop_img.jpg', target_size=(224, 224))
82
- crop_img = img_to_array(crop_img)
83
- crop_img = np.expand_dims(crop_img, axis=0)
84
- crop_img = preprocess_input(crop_img)
85
- img_encode = vgg_face(crop_img)
86
-
87
- embed = tf.keras.backend.eval(img_encode)
88
- person = classifier_model.predict(embed)
89
- confidence = np.max(person)
90
- name = person_rep[np.argmax(person)]
91
- os.remove('crop_img.jpg')
92
-
 
93
  if confidence > 0.9:
94
  cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0), 2)
95
  img = cv2.putText(img, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 255), 2, cv2.LINE_AA)
96
  img = cv2.putText(img, str(confidence), (left, bottom + 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)
97
 
 
98
  st.image(cv2.cvtColor(img, cv2.COLOR_BGR2RGB), caption='Imagen procesada', use_column_width=True)
 
11
  from tensorflow.keras.models import Sequential
12
  from tensorflow.keras.layers import Dense, BatchNormalization, Activation, Dropout
13
 
14
+ # Ruta al modelo de clasificaci贸n facial preentrenado
15
  model_path = './face_classifier_model.h5'
16
+ # Ruta al modelo VGG-Face
17
  vgg_face_path = './vgg_face_model.h5'
18
+
19
+ # Cargar el modelo VGG-Face preentrenado
20
  vgg_face = load_model(vgg_face_path)
21
 
22
+ # Cargar el detector de rostros de Dlib basado en CNN
23
  dnnFaceDetector = dlib.cnn_face_detection_model_v1("mmod_human_face_detector.dat")
24
 
25
+ # Cargar el modelo de clasificaci贸n sin compilar
26
  classifier_model = tf.keras.models.load_model(model_path, compile=False)
27
 
28
+ # Compilar el modelo de clasificaci贸n con los par谩metros adecuados
29
  classifier_model.compile(loss=tf.keras.losses.SparseCategoricalCrossentropy(),
30
  optimizer='nadam',
31
  metrics=['accuracy'])
32
 
33
+ # Diccionario que asigna los 铆ndices de las clases a nombres de personas
34
+ person_rep = {0: 'NataliePortman',
35
+ 1: 'HughJackman',
36
+ 2: 'JohnnyDepp',
37
+ 3: 'TomCruise',
38
+ 4: 'JenniferLawrence',
39
+ 5: 'MeganFox',
40
+ 6: 'WillSmith',
41
+ 7: 'TomHanks',
42
+ 8: 'KateWinslet',
43
+ 9: 'ScarlettJohansson',
44
+ 10: 'DenzelWashington',
45
+ 11: 'LeonardoDiCaprio',
46
+ 12: 'RobertDowneyJr',
47
+ 13: 'NicoleKidman',
48
+ 14: 'SandraBullock',
49
+ 15: 'BradPitt',
50
+ 16: 'AngelinaJolie'}
51
+
52
+ # Funci贸n para predecir la clase de una imagen
53
  def predict_image(image_path):
54
+ img = load_img(image_path, target_size=(224, 224)) # Cargar la imagen y redimensionarla
55
+ img = img_to_array(img) # Convertir la imagen a un array de numpy
56
+ img = np.expand_dims(img, axis=0) # A帽adir una dimensi贸n extra para el batch
57
+ img = preprocess_input(img) # Preprocesar la imagen para VGG-Face
58
 
59
+ img_encode = vgg_face(img) # Obtener los embeddings de la imagen
60
+ predictions = classifier_model.predict(img_encode) # Realizar la predicci贸n
61
  return predictions
62
 
63
+ # Interfaz de usuario con Streamlit
64
  st.title("Reconocimiento Facial")
65
  st.write("Sube una imagen y el modelo intentar谩 identificar el rostro.")
66
 
67
+ # Subida de archivo
68
  uploaded_file = st.file_uploader("Elige una imagen...", type="jpg")
69
 
70
+ # Si se sube un archivo
71
  if uploaded_file is not None:
72
+ file_bytes = np.asarray(bytearray(uploaded_file.read()), dtype=np.uint8) # Leer la imagen subida como un array de bytes
73
+ img = cv2.imdecode(file_bytes, 1) # Decodificar la imagen
74
 
75
+ gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Convertir la imagen a escala de grises
76
+ rects = dnnFaceDetector(gray, 1) # Detectar rostros en la imagen
77
 
78
+ # Recorrer todos los rostros detectados
79
  for (i, rect) in enumerate(rects):
80
+ left = rect.rect.left() # Coordenada x1
81
+ top = rect.rect.top() # Coordenada y1
82
+ right = rect.rect.right() # Coordenada x2
83
+ bottom = rect.rect.bottom() # Coordenada y2
84
  width = right - left
85
  height = bottom - top
86
+ img_crop = img[top:top + height, left:left + width] # Recortar el rostro de la imagen
87
+ cv2.imwrite('crop_img.jpg', img_crop) # Guardar el rostro recortado temporalmente
88
+
89
+ crop_img = load_img('crop_img.jpg', target_size=(224, 224)) # Cargar y redimensionar el rostro recortado
90
+ crop_img = img_to_array(crop_img) # Convertir el rostro a un array de numpy
91
+ crop_img = np.expand_dims(crop_img, axis=0) # A帽adir una dimensi贸n extra para el batch
92
+ crop_img = preprocess_input(crop_img) # Preprocesar la imagen para VGG-Face
93
+ img_encode = vgg_face(crop_img) # Obtener los embeddings del rostro
94
+
95
+ embed = tf.keras.backend.eval(img_encode) # Evaluar los embeddings
96
+ person = classifier_model.predict(embed) # Realizar la predicci贸n
97
+ confidence = np.max(person) # Obtener la confianza de la predicci贸n
98
+ name = person_rep[np.argmax(person)] # Obtener el nombre de la persona predicha
99
+ os.remove('crop_img.jpg') # Eliminar la imagen recortada temporalmente
100
+
101
+ # Si la confianza es mayor a 0.9, dibujar el cuadro y el nombre en la imagen original
102
  if confidence > 0.9:
103
  cv2.rectangle(img, (left, top), (right, bottom), (0, 255, 0), 2)
104
  img = cv2.putText(img, name, (left, top - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 255), 2, cv2.LINE_AA)
105
  img = cv2.putText(img, str(confidence), (left, bottom + 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)
106
 
107
+ # Mostrar la imagen procesada en la interfaz de Streamlit
108
  st.image(cv2.cvtColor(img, cv2.COLOR_BGR2RGB), caption='Imagen procesada', use_column_width=True)
face_classifier_model.h5 CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:4fd6ffcd4f98f5074cad8adcaa7e7897885f65ff5f446ab368d834098d3639a1
3
  size 3219008
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4cb54ed3e17fb9d34f6320352e883e6222a8f4cbe173e96c10fa263e48083eb2
3
  size 3219008
vgg_face_model.h5 DELETED
@@ -1,3 +0,0 @@
1
- version https://git-lfs.github.com/spec/v1
2
- oid sha256:98a199deb2628a8f0c39b4142a338248b104e1749225b6963c1c7b41fbe20991
3
- size 580104848