ia_emotional/app.py

98 lines
3.4 KiB
Python
Raw Permalink Normal View History

2024-08-27 23:20:17 +02:00
import os
from PIL import Image
2024-08-27 23:48:42 +02:00
import numpy as np
from tensorflow.keras.preprocessing.image import load_img, img_to_array
2024-08-27 23:20:17 +02:00
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense
2024-08-27 23:48:42 +02:00
import sys
# Chemin vers vos données
data_dir = 'donnees'
# Chargement des images de personnes contentes
happy_dir = os.path.join(data_dir, 'happy')
images_happy = []
for filename in os.listdir(happy_dir):
img_path = os.path.join(happy_dir, filename)
img = load_img(img_path, target_size=(224, 224))
img_array = img_to_array(img)
images_happy.append(img_array)
x_happy = np.array(images_happy) / 255.0
y_happy = np.ones((len(images_happy),)) # étiquettes : tous les images sont de personnes contentes (1)
# Chargement des images de personnes tristes
sad_dir = os.path.join(data_dir, 'sad')
images_sad = []
for filename in os.listdir(sad_dir):
img_path = os.path.join(sad_dir, filename)
img = load_img(img_path, target_size=(224, 224))
img_array = img_to_array(img)
images_sad.append(img_array)
x_sad = np.array(images_sad) / 255.0
y_sad = np.zeros((len(images_sad),)) # étiquettes : tous les images sont de personnes tristes (0)
# Préparation des données d'entraînement et de test
x_happy = np.array(images_happy) / 255.0
y_happy = np.ones((len(images_happy),)) # étiquettes : tous les images sont de personnes contentes (1)
x_sad = np.array(images_sad) / 255.0
y_sad = np.zeros((len(images_sad),)) # étiquettes : tous les images sont de personnes tristes (0)
2024-08-27 23:20:17 +02:00
2024-08-27 23:48:42 +02:00
x_train = np.concatenate((x_happy, x_sad))
y_train = np.concatenate((y_happy, y_sad))
# Séparation des données en entraînement et de test
train_size = int(0.8 * len(x_train))
x_train, x_test = x_train[:train_size], x_train[train_size:]
y_train, y_test = y_train[:train_size], y_train[train_size:]
# Création du modèle de reconnaissance d'émotion
2024-08-27 23:20:17 +02:00
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(224, 224, 3)))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(128, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
2024-08-27 23:48:42 +02:00
model.add(Dense(1, activation='sigmoid'))
2024-08-27 23:20:17 +02:00
# Compilation du modèle
2024-08-27 23:48:42 +02:00
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
2024-08-27 23:20:17 +02:00
# Entraînement du modèle
2024-08-27 23:48:42 +02:00
model.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_test, y_test))
# Évaluation du modèle
loss, accuracy = model.evaluate(x_test, y_test)
print(f'Pertinence : {accuracy:.2f}')
# Chargement de l'image à tester
img_path = sys.argv[1]
# Ouvre l'image avec OpenCV
img = load_img(img_path, target_size=(224, 224))
# Convertit l'image en tableau NumPy
img_array = img_to_array(img)
# Prétraitement de l'image (normalisation des pixels)
img_array = img_array / 255.0
# Prédiction de l'émotion avec le modèle
prediction = model.predict(np.array([img_array]))
# Récupération de la probabilité de contenu et de tristesse
content_prob = prediction[0][0]
sadness_prob = 1 - content_prob
print(f"Probabilité de contenu : {content_prob:.2f}")
print(f"Probabilité de tristesse : {sadness_prob:.2f}")
# Vous pouvez également utiliser une fonction pour déterminer si l'émotion est plus proche du contenu ou de la tristesse
if content_prob > sadness_prob:
print("L'image semble être un sourire !")
else:
print("L'image semble être une expression triste.")