CARIA.2.1

Update for the final presentation
huge change with previous version
This commit is contained in:
ccunatbrule
2024-09-03 12:08:48 +02:00
parent 194398cebc
commit 3e6785fec2
207 changed files with 57229 additions and 409 deletions

View File

@@ -0,0 +1,117 @@
import tensorflow as tf
from tensorflow.keras import layers, models
import numpy as np
from sklearn.utils import shuffle
import os
import cv2
import csv
import dataset_params_edition as dataset
# Taille des images
size = 60
# Nombre total d'images à générer
nombre_images_a_generer = 2000
# Chemin vers le répertoire contenant les images de panneaux
dir_images_panneaux = "server-trainer/images/autres_panneaux"
dir_images_genere_panneaux = "server-trainer/images/genere_autres_panneaux"
csv_file_path = "server-trainer/images/genere_autres_panneaux_labels.csv"
# Fonction pour lire les images de panneaux à partir du répertoire spécifié
def lire_images_panneaux(dir_images_panneaux, size=None):
print(f"Lecture des images depuis le répertoire : {dir_images_panneaux}")
tab_panneau = []
tab_image_panneau = []
if not os.path.exists(dir_images_panneaux):
quit(f"Le répertoire d'image n'existe pas: {dir_images_panneaux}")
files = os.listdir(dir_images_panneaux)
if files is None or len(files) == 0:
quit(f"Le répertoire d'image est vide: {dir_images_panneaux}")
for file in sorted(files):
if file.endswith("png"):
tab_panneau.append(file.split(".")[0])
image = cv2.imread(os.path.join(dir_images_panneaux, file))
if size is not None:
image = cv2.resize(image, (size, size), cv2.INTER_LANCZOS4)
tab_image_panneau.append(image)
return tab_panneau, tab_image_panneau
# Supprimer les images existantes et le fichier CSV
if os.path.exists(dir_images_genere_panneaux):
for file in os.listdir(dir_images_genere_panneaux):
file_path = os.path.join(dir_images_genere_panneaux, file)
if os.path.isfile(file_path):
os.remove(file_path)
if os.path.exists(csv_file_path):
os.remove(csv_file_path)
tab_panneau, tab_image_panneau = lire_images_panneaux(dir_images_panneaux, size)
print(f"Nombre d'images lues : {len(tab_image_panneau)}")
tab_images = np.array([]).reshape(0, size, size, 3)
tab_labels = []
images_par_panneau = nombre_images_a_generer // len(tab_image_panneau)
print(f"Nombre d'images à générer par panneau : {images_par_panneau}")
print("Génération des images modifiées...")
csv_data = [] # Liste pour stocker les données du CSV
for id, image in enumerate(tab_image_panneau):
lot = []
for i in range(images_par_panneau):
lot.append(dataset.modif_img(image))
lot = np.array(lot)
tab_images = np.concatenate([tab_images, lot])
tab_labels = np.concatenate([tab_labels, np.full(len(lot), id)])
print(f"Nombre total d'images générées : {len(tab_images)}")
tab_panneau = np.array(tab_panneau)
tab_images = np.array(tab_images, dtype=np.float32) / 255
tab_labels = np.array(tab_labels).reshape([-1, 1])
tab_images, tab_labels = shuffle(tab_images, tab_labels)
print("Données mélangées.")
print(f"Sauvegarde des images générées dans : {dir_images_genere_panneaux}")
if not os.path.exists(dir_images_genere_panneaux):
os.makedirs(dir_images_genere_panneaux)
for i in range(len(tab_images)):
# Générer un nom de fichier unique
file_name = "{}_{}.png".format(i, tab_panneau[int(tab_labels[i])])
# Enregistrer l'image dans le répertoire de sortie
cv2.imwrite(os.path.join(dir_images_genere_panneaux, file_name), tab_images[i] * 255.0)
# Ajouter les données au CSV
label = "OP" + str(i)
csv_data.append([file_name, label])
print("Toutes les images ont été sauvegardées.")
print(f"Nombre total d'images sauvegardées : {len(tab_images)}")
# Écrire les données dans le fichier CSV
print(f"Écriture des labels dans le fichier CSV : {csv_file_path}")
with open(csv_file_path, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["filename", "label"]) # Écrire l'en-tête
writer.writerows(csv_data) # Écrire les données
print("Fichier CSV généré.")
print("Affichage des images générées...")
for i in range(len(tab_images)):
cv2.imshow("panneau", tab_images[i])
print(f"label: {tab_labels[i][0]}, panneau: {tab_panneau[int(tab_labels[i])]}")
key = cv2.waitKey(0) & 0xFF
if key == ord('q'):
print("Sortie demandée par l'utilisateur.")
break
cv2.destroyAllWindows()
print("Terminé.")

View File

@@ -0,0 +1,97 @@
import cv2
import numpy as np
import random
import os
# Taille des images
size = 60
# Chemin vers la vidéo et le répertoire de sortie
video = "server-ia/data/videos/autoroute.mp4"
dir_images_genere_sans_panneaux = "server-trainer/images/genere_sans_panneaux"
# Nombre total d'images à générer
nbr_image = 2000
# Création du répertoire de sortie s'il n'existe pas
if not os.path.isdir(dir_images_genere_sans_panneaux):
os.makedirs(dir_images_genere_sans_panneaux)
print(f"Répertoire créé : {dir_images_genere_sans_panneaux}")
# Vérification de l'existence de la vidéo
if not os.path.exists(video):
print(f"Vidéo non présente : {video}")
quit()
print(f"Vidéo trouvée : {video}")
cap = cv2.VideoCapture(video)
if not cap.isOpened():
print(f"Erreur lors de l'ouverture de la vidéo : {video}")
quit()
# Calcul du nombre d'images à générer par frame
nbr_frame_total = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
nbr_image_par_frame = int(nbr_image / nbr_frame_total) + 1
print(f"Nombre d'images à générer : {nbr_image}")
print(f"Nombre d'images à générer par frame : {nbr_image_par_frame}")
id = 0
# Variables pour calculer les dimensions globales
dimensions = []
min_w = float('inf')
max_w = 0
min_h = float('inf')
max_h = 0
while True:
ret, frame = cap.read()
if not ret:
print("Fin de la vidéo ou erreur de lecture.")
break
h, w, c = frame.shape
# Mettre à jour les dimensions minimales et maximales
min_w = min(min_w, w)
max_w = max(max_w, w)
min_h = min(min_h, h)
max_h = max(max_h, h)
# Ajouter les dimensions de la frame
dimensions.append((w, h, c))
for _ in range(nbr_image_par_frame):
x = random.randint(0, w - size)
y = random.randint(0, h - size)
img = frame[y:y + size, x:x + size]
# Sauvegarde de l'image
img_filename = os.path.join(dir_images_genere_sans_panneaux, f"{id}.png")
cv2.imwrite(img_filename, img)
id += 1
if id >= nbr_image:
print(f"Nombre d'images générées atteint : {nbr_image}")
break
if id >= nbr_image:
break
cap.release()
# Affichage du nombre total d'images sauvegardées et de l'emplacement du répertoire
print(f"Nombre total d'images sauvegardées : {id}")
print(f"Emplacement des images sauvegardées : {dir_images_genere_sans_panneaux}")
# Calcul des dimensions globales
average_w = np.mean([w for w, h, c in dimensions])
average_h = np.mean([h for w, h, c in dimensions])
# Affichage des statistiques globales
print(f"Dimensions minimales : {min_w}x{min_h}")
print(f"Dimensions maximales : {max_w}x{max_h}")
print(f"Dimensions moyennes : {average_w:.2f}x{average_h:.2f}")
print("Libération des ressources et fin du traitement.")

View File

@@ -0,0 +1,117 @@
import tensorflow as tf
from tensorflow.keras import layers, models
import numpy as np
from sklearn.utils import shuffle
import os
import cv2
import csv
import dataset_params_edition as dataset
# Taille des images
size = 60
# Nombre total d'images à générer
nombre_images_a_generer = 2000
# Chemin vers le répertoire contenant les images de panneaux
dir_images_panneaux = "server-trainer/images/vitesse_panneaux"
dir_images_genere_panneaux = "server-trainer/images/genere_vitesse_panneaux"
csv_file_path = "server-trainer/images/genere_vitesse_panneaux_labels.csv"
# Fonction pour lire les images de panneaux à partir du répertoire spécifié
def lire_images_panneaux(dir_images_panneaux, size=None):
print(f"Lecture des images depuis le répertoire : {dir_images_panneaux}")
tab_panneau = []
tab_image_panneau = []
if not os.path.exists(dir_images_panneaux):
quit(f"Le répertoire d'image n'existe pas: {dir_images_panneaux}")
files = os.listdir(dir_images_panneaux)
if files is None or len(files) == 0:
quit(f"Le répertoire d'image est vide: {dir_images_panneaux}")
for file in sorted(files):
if file.endswith("png"):
tab_panneau.append(file.split(".")[0])
image = cv2.imread(os.path.join(dir_images_panneaux, file))
if size is not None:
image = cv2.resize(image, (size, size), cv2.INTER_LANCZOS4)
tab_image_panneau.append(image)
return tab_panneau, tab_image_panneau
# Supprimer les images existantes et le fichier CSV
if os.path.exists(dir_images_genere_panneaux):
for file in os.listdir(dir_images_genere_panneaux):
file_path = os.path.join(dir_images_genere_panneaux, file)
if os.path.isfile(file_path):
os.remove(file_path)
if os.path.exists(csv_file_path):
os.remove(csv_file_path)
tab_panneau, tab_image_panneau = lire_images_panneaux(dir_images_panneaux, size)
print(f"Nombre d'images lues : {len(tab_image_panneau)}")
tab_images = np.array([]).reshape(0, size, size, 3)
tab_labels = []
images_par_panneau = nombre_images_a_generer // len(tab_image_panneau)
print(f"Nombre d'images à générer par panneau : {images_par_panneau}")
print("Génération des images modifiées...")
csv_data = [] # Liste pour stocker les données du CSV
for id, image in enumerate(tab_image_panneau):
lot = []
for i in range(images_par_panneau):
lot.append(dataset.modif_img(image))
lot = np.array(lot)
tab_images = np.concatenate([tab_images, lot])
tab_labels = np.concatenate([tab_labels, np.full(len(lot), id)])
print(f"Nombre total d'images générées : {len(tab_images)}")
tab_panneau = np.array(tab_panneau)
tab_images = np.array(tab_images, dtype=np.float32) / 255
tab_labels = np.array(tab_labels).reshape([-1, 1])
tab_images, tab_labels = shuffle(tab_images, tab_labels)
print("Données mélangées.")
print(f"Sauvegarde des images générées dans : {dir_images_genere_panneaux}")
if not os.path.exists(dir_images_genere_panneaux):
os.makedirs(dir_images_genere_panneaux)
for i in range(len(tab_images)):
# Générer un nom de fichier unique
file_name = "{}_{}.png".format(i, tab_panneau[int(tab_labels[i])])
# Enregistrer l'image dans le répertoire de sortie
cv2.imwrite(os.path.join(dir_images_genere_panneaux, file_name), tab_images[i] * 255.0)
# Ajouter les données au CSV
label = "VP" + str(i)
csv_data.append([file_name, label])
print("Toutes les images ont été sauvegardées.")
print(f"Nombre total d'images sauvegardées : {len(tab_images)}")
# Écrire les données dans le fichier CSV
print(f"Écriture des labels dans le fichier CSV : {csv_file_path}")
with open(csv_file_path, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["filename", "label"]) # Écrire l'en-tête
writer.writerows(csv_data) # Écrire les données
print("Fichier CSV généré.")
print("Affichage des images générées...")
for i in range(len(tab_images)):
cv2.imshow("panneau", tab_images[i])
print(f"label: {tab_labels[i][0]}, panneau: {tab_panneau[int(tab_labels[i])]}")
key = cv2.waitKey(0) & 0xFF
if key == ord('q'):
print("Sortie demandée par l'utilisateur.")
break
cv2.destroyAllWindows()
print("Terminé.")

View File

@@ -0,0 +1,92 @@
import numpy as np
import cv2
import random
import multiprocessing
from multiprocessing import Pool
def bruit(image_orig):
h, w, c = image_orig.shape
n = np.random.randn(h, w, c) * random.randint(5, 30)
return np.clip(image_orig + n, 0, 255).astype(np.uint8)
def change_gamma(image, alpha=1.0, beta=0.0):
return np.clip(alpha * image + beta, 0, 255).astype(np.uint8)
def modif_img(img):
h, w, c = img.shape
r_color = [np.random.randint(255), np.random.randint(255), np.random.randint(255)]
img = np.where(img == [142, 142, 142], r_color, img).astype(np.uint8)
if np.random.randint(3):
k_max = 3
kernel_blur = np.random.randint(k_max) * 2 + 1
img = cv2.GaussianBlur(img, (kernel_blur, kernel_blur), 0)
M = cv2.getRotationMatrix2D((int(w / 2), int(h / 2)), random.randint(-10, 10), 1)
img = cv2.warpAffine(img, M, (w, h))
if np.random.randint(2):
a = int(max(w, h) / 5) + 1
pts1 = np.float32([[0, 0], [w, 0], [0, h], [w, h]])
pts2 = np.float32([[0 + random.randint(-a, a), 0 + random.randint(-a, a)],
[w - random.randint(-a, a), 0 + random.randint(-a, a)],
[0 + random.randint(-a, a), h - random.randint(-a, a)],
[w - random.randint(-a, a), h - random.randint(-a, a)]])
M = cv2.getPerspectiveTransform(pts1,pts2)
img = cv2.warpPerspective(img, M, (w, h))
if np.random.randint(2):
r = random.randint(0, 5)
h2 = int(h * 0.9)
w2 = int(w * 0.9)
if r == 0:
img = img[0:w2, 0:h2]
elif r == 1:
img = img[w - w2:w, 0:h2]
elif r == 2:
img = img[0:w2, h - h2:h]
elif r == 3:
img = img[w - w2:w, h - h2:h]
img = cv2.resize(img, (h, w))
if np.random.randint(2):
r = random.randint(1, int(max(w, h) * 0.15))
img = img[r:w - r, r:h - r]
img = cv2.resize(img, (h, w))
if not np.random.randint(4):
t = np.empty((h, w, c), dtype=np.float32)
for i in range(h):
for j in range(w):
for k in range(c):
t[i][j][k] = (i / h)
M = cv2.getRotationMatrix2D((int(w / 2), int(h / 2)), np.random.randint(4) * 90, 1)
t = cv2.warpAffine(t, M, (w, h))
img = (cv2.multiply((img / 255).astype(np.float32), t) * 255).astype(np.uint8)
img = change_gamma(img, random.uniform(0.6, 1.0), -np.random.randint(50))
if not np.random.randint(4):
p = (15 + np.random.randint(10)) / 100
img = (img * p + 50 * (1 - p)).astype(np.uint8) + np.random.randint(100)
img = bruit(img)
return img
def create_lot_img(image, nbr, nbr_thread=None):
if nbr_thread is None:
nbr_thread = multiprocessing.cpu_count()
# Convert the image to a bytes-like object to avoid issues with multiprocessing
image_bytes = np.array(image, dtype=np.uint8).tobytes()
def modif_img_from_bytes(image_bytes):
img = np.frombuffer(image_bytes, dtype=np.uint8).reshape(image.shape)
return modif_img(img)
with Pool(nbr_thread) as p:
lot_result = p.map(modif_img_from_bytes, [image_bytes] * nbr)
return lot_result