Skip to content
Snippets Groups Projects
Commit 48365a14 authored by Mohyeddine2's avatar Mohyeddine2
Browse files

rdf commiting

parents
Branches
No related tags found
No related merge requests found
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="PYTHON_MODULE" version="4">
<component name="NewModuleRootManager">
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<component name="InspectionProjectProfileManager">
<settings>
<option name="USE_PROJECT_PROFILE" value="false" />
<version value="1.0" />
</settings>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Black">
<option name="sdkName" value="C:\Users\mohye\anaconda3" />
</component>
<component name="ProjectRootManager" version="2" project-jdk-name="C:\Users\mohye\anaconda3" project-jdk-type="Python SDK" />
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/RdfProjects.iml" filepath="$PROJECT_DIR$/.idea/RdfProjects.iml" />
</modules>
</component>
</project>
\ No newline at end of file
2.avif 0 → 100644
File added
import cv2
import numpy as np
#rom skimage import color, filters, morphology
import matplotlib.pyplot as plt
import mediapipe as mp
# Charger l'image
image_path = 'image 1.jpg'
image = cv2.imread(image_path)
# 1. Prétraitement - Conversion en niveaux de gris
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 2. Segmentation - Seuillage adaptatif pour isoler la main
#_, binary_image = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
edges = cv2.Canny(gray_image, 40, 150)
#binary_image = cv2.bitwise_not(binary_image)
# Affichage de l'image binaire
plt.figure(figsize=(8, 8))
plt.imshow(edges, cmap="gray")
plt.title("Image segmentée ")
plt.axis("off")
plt.show()
mp_hands = mp.solutions.hands
mp_drawing = mp.solutions.drawing_utils
with mp_hands.Hands(static_image_mode=True, max_num_hands=1, min_detection_confidence=0.5) as hands:
results = hands.process(edges)
# Vérifie si une main a été détectée
if results.multi_hand_landmarks:
for hand_landmarks in results.multi_hand_landmarks:
# Dessiner les points clés et les connexions sur l'image
annotated_image = image.copy()
mp_drawing.draw_landmarks(
annotated_image,
hand_landmarks,
mp_hands.HAND_CONNECTIONS,
mp_drawing.DrawingSpec(color=(0, 255, 0), thickness=2, circle_radius=3),
mp_drawing.DrawingSpec(color=(0, 0, 255), thickness=2, circle_radius=2)
)
# Affichage des coordonnées des points clés (optionnel)
for idx, landmark in enumerate(hand_landmarks.landmark):
print(f"Point {idx}: (x: {landmark.x}, y: {landmark.y}, z: {landmark.z})")
# Affichage de l'image annotée
plt.figure(figsize=(8, 8))
plt.imshow(cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB))
plt.title("Squelette de la main avec MediaPipe")
plt.axis("off")
plt.show()
else:
print("Aucune main détectée dans l'image.")
\ No newline at end of file
import cv2
import numpy as np
from mypy.messages import best_matches
images=[]
for i in range(5):
path = "image "+str(i+1)+".jpg"
image = cv2.imread(path)
images.append(image)
def calculate_hu_moments(images):
moments_list = []
for image in images:
smoothed_img = cv2.GaussianBlur(image, (3, 3), 0)
resized_img = cv2.resize(smoothed_img, (318, 513))
if len(smoothed_img.shape) == 3 and smoothed_img.shape[2] == 3:
resized_img_gray = cv2.cvtColor(resized_img, cv2.COLOR_BGR2GRAY)
else:
resized_img_gray = smoothed_img
mask = np.zeros_like(resized_img_gray, dtype=np.uint8)
mask[-100:, :] = 255
resized_img_gray = cv2.bitwise_or(resized_img_gray, mask)
_, binary = cv2.threshold(resized_img_gray, 127, 255, cv2.THRESH_BINARY)
moments = cv2.moments(binary)
huMoments = cv2.HuMoments(moments)
for i in range(len(huMoments)):
if huMoments[i] != 0:
huMoments[i] = -1 * np.sign(huMoments[i]) * np.log10(abs(huMoments[i]))
else:
huMoments[i] = 0
moments_list.append(huMoments)
return moments_list
def compare_hu_moments(moment_known, moment_unknown):
distances = {
'Euclidean': [],
'Manhattan': [],
'Chebyshev': []
}
for moments1 in moment_known:
euclidean_distance = np.sqrt(np.sum((moments1 - moment_unknown) ** 2))
manhattan_distance = np.sum(np.abs(moments1 - moment_unknown))
chebyshev_distance = np.max(np.abs(moments1 - moment_unknown))
distances['Euclidean'].append(euclidean_distance)
distances['Manhattan'].append(manhattan_distance)
distances['Chebyshev'].append(chebyshev_distance)
return distances
def best_matching(moment_known, moment_unknown):
distances = compare_hu_moments(moment_known, moment_unknown)
best_matches = {}
for metric, values in distances.items():
best_index = np.argmin(values)
min_distance = values[best_index]
best_matches[metric] = {
"index": best_index,
"distance": min_distance,
"moments": moment_known[best_index]
}
print(metric, best_index, "signe : ",best_index+1 )
return best_matches
moments_list = calculate_hu_moments(images)
img = cv2.imread("image 2.jpg")
moment_unknown = calculate_hu_moments(img)
distances = compare_hu_moments(moments_list, moment_unknown)
best_matches = best_matching(moments_list, moment_unknown)
#cv2.putText(img, f"Number: {index}", (20, 20),
# cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 1)
cv2.imshow('image', img)
cv2.imshow('image unkown',images[3])
cv2.waitKey(0)
cv2.destroyAllWindows()
import cv2
import numpy as np
import os
import matplotlib.pyplot as plt
def calculate_histogram(image, bins=32):
hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
hist = cv2.calcHist([hsv_image], [0, 1], None, [bins, bins], [0, 180, 0, 256])
return cv2.normalize(hist, hist).flatten()
def intersection_hist(hist1, hist2):
return cv2.compareHist(hist1, hist2, cv2.HISTCMP_INTERSECT)
def bhattacharyya_distance(hist1, hist2):
return cv2.compareHist(hist1, hist2, cv2.HISTCMP_BHATTACHARYYA)
def minkowski_distance(hist1, hist2, p=2):
return np.sum(np.abs(hist1 - hist2) ** p) ** (1 / p)
def matusita_distance(hist1, hist2):
return np.sqrt(np.sum((np.sqrt(hist1) - np.sqrt(hist2)) ** 2))
def cosine_distance(hist1, hist2):
cosine_similarity = np.dot(hist1, hist2) / (np.linalg.norm(hist1) * np.linalg.norm(hist2))
return cosine_similarity
def emd(hist1, hist2):
bins1 = np.array([[i, hist1[i]] for i in range(len(hist1))], dtype=np.float32)
bins2 = np.array([[i, hist2[i]] for i in range(len(hist2))], dtype=np.float32)
emd_value, _, _ = cv2.EMD(bins1, bins2, cv2.DIST_L2)
return emd_value
def find_minimum_distance(reference_image_path, scene_folder, bins=32):
# Charger l'image de référence
reference_image = cv2.imread(reference_image_path)
if reference_image is None:
raise FileNotFoundError(f"Impossible de charger l'image : {reference_image_path}")
reference_hist = calculate_histogram(reference_image, bins)
valid_extensions = ('.jpg', '.jpeg', '.png', '.bmp', '.tiff')
min_distances = {
'Bhattacharyya': float('inf'),
'Minkowski': float('inf'),
'Matusita': float('inf'),
'Cosine': float('inf'),
'EMD': float('inf')
}
closest_images = {
'Bhattacharyya': None,
'Minkowski': None,
'Matusita': None,
'Cosine': None,
'EMD': None
}
for filename in os.listdir(scene_folder):
if filename.lower().endswith(valid_extensions):
file_path = os.path.join(scene_folder, filename)
target_image = cv2.imread(file_path)
if target_image is None:
print(f"Erreur : Impossible de charger l'image {file_path}")
continue
target_hist = calculate_histogram(target_image, bins)
distances = {
'Bhattacharyya': bhattacharyya_distance(reference_hist, target_hist),
'Minkowski': minkowski_distance(reference_hist, target_hist),
'Matusita': matusita_distance(reference_hist, target_hist),
'Cosine': cosine_distance(reference_hist, target_hist),
'EMD': emd(reference_hist, target_hist)
}
for metric, distance in distances.items():
if distance < min_distances[metric]:
min_distances[metric] = distance
closest_images[metric] = file_path
return min_distances, closest_images, reference_image,distances
def visualize_results(reference_image, closest_images, min_distances):
metrics = list(closest_images.keys())
fig, axes = plt.subplots(1, len(metrics) + 1, figsize=(15, 5))
axes[0].imshow(cv2.cvtColor(reference_image, cv2.COLOR_BGR2RGB))
axes[0].set_title("Image de Référence")
axes[0].axis('off')
for i, metric in enumerate(metrics):
closest_image = cv2.imread(closest_images[metric])
if closest_image is not None:
axes[i + 1].imshow(cv2.cvtColor(closest_image, cv2.COLOR_BGR2RGB))
axes[i + 1].set_title(f"{metric}\n{min_distances[metric]:.4f}")
else:
axes[i + 1].set_title(f"{metric}\nImage non trouvée")
axes[i + 1].axis('off')
plt.tight_layout()
plt.show()
reference_image_path = "Scene1/158.jpg"
scene_folder = "Scene1"
min_distances, closest_images, reference_image, dis = find_minimum_distance(reference_image_path, scene_folder)
print("Distances minimales et images correspondantes :")
for metric, distance in min_distances.items():
print(f"{metric} : {distance:.4f} (Image : {closest_images[metric]})")
visualize_results(reference_image, closest_images, min_distances)
TP1.py 0 → 100644
import cv2
import numpy as np
#rom skimage import color, filters, morphology
import matplotlib.pyplot as plt
import mediapipe as mp
# Charger l'image
image_path = 'image 1.jpg'
image = cv2.imread(image_path)
# 1. Prétraitement - Conversion en niveaux de gris
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 2. Segmentation - Seuillage adaptatif pour isoler la main
#_, binary_image = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
edges = cv2.Canny(gray_image, 40, 150)
#binary_image = cv2.bitwise_not(binary_image)
# Affichage de l'image binaire
plt.figure(figsize=(8, 8))
plt.imshow(edges, cmap="gray")
plt.title("Image segmentée ")
plt.axis("off")
plt.show()
mp_hands = mp.solutions.hands
mp_drawing = mp.solutions.drawing_utils
with mp_hands.Hands(static_image_mode=True, max_num_hands=1, min_detection_confidence=0.5) as hands:
results = hands.process(edges)
# Vérifie si une main a été détectée
if results.multi_hand_landmarks:
for hand_landmarks in results.multi_hand_landmarks:
# Dessiner les points clés et les connexions sur l'image
annotated_image = image.copy()
mp_drawing.draw_landmarks(
annotated_image,
hand_landmarks,
mp_hands.HAND_CONNECTIONS,
mp_drawing.DrawingSpec(color=(0, 255, 0), thickness=2, circle_radius=3),
mp_drawing.DrawingSpec(color=(0, 0, 255), thickness=2, circle_radius=2)
)
# Affichage des coordonnées des points clés (optionnel)
for idx, landmark in enumerate(hand_landmarks.landmark):
print(f"Point {idx}: (x: {landmark.x}, y: {landmark.y}, z: {landmark.z})")
# Affichage de l'image annotée
plt.figure(figsize=(8, 8))
plt.imshow(cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB))
plt.title("Squelette de la main avec MediaPipe")
plt.axis("off")
plt.show()
else:
print("Aucune main détectée dans l'image.")
\ No newline at end of file
TP2.py 0 → 100644
TP3.py 0 → 100644
image 1.jpg

25.5 KiB

image 2.jpg

6.78 KiB

image 3.jpg

8.19 KiB

image 4.jpg

8.33 KiB

image 5.jpg

8.81 KiB

image6.jpg

13.3 KiB

imagecom.jpg

30.2 KiB

sd.py 0 → 100644
import networkx as nx
import matplotlib.pyplot as plt
# Définir les nœuds (articulations de la main) et leurs connexions (arêtes)
nodes = {
1: "Poignet",
2: "Base du pouce",
3: "Pouce 1",
4: "Pouce 2",
5: "Extrémité pouce",
6: "Base de l'index",
7: "Index 1",
8: "Index 2",
9: "Extrémité index",
10: "Base du majeur",
11: "Majeur 1",
12: "Majeur 2",
13: "Extrémité majeur",
14: "Base de l'annulaire",
15: "Annulaire 1",
16: "Annulaire 2",
17: "Extrémité annulaire",
18: "Base de l'auriculaire",
19: "Auriculaire 1",
20: "Auriculaire 2",
21: "Extrémité auriculaire"
}
# Arêtes reliant les nœuds (structure de la main)
edges = [
(1, 2), (2, 3), (3, 4), (4, 5), # Pouce
(1, 6), (6, 7), (7, 8), (8, 9), # Index
(1, 10), (10, 11), (11, 12), (12, 13), # Majeur
(1, 14), (14, 15), (15, 16), (16, 17), # Annulaire
(1, 18), (18, 19), (19, 20), (20, 21) # Auriculaire
]
# Créer un graphe
G = nx.Graph()
G.add_nodes_from(nodes.keys())
G.add_edges_from(edges)
# Ajouter des étiquettes aux nœuds pour la visualisation
node_labels = {key: value for key, value in nodes.items()}
# Visualisation du graphe
plt.figure(figsize=(10, 8))
pos = nx.spring_layout(G, seed=42) # Générer une disposition des nœuds
# Dessiner le graphe
nx.draw(G, pos, with_labels=False, node_color="skyblue", node_size=1000, edge_color="gray", linewidths=1, font_size=15)
nx.draw_networkx_labels(G, pos, labels=node_labels, font_size=10, font_color="black")
plt.title("Graphe représentant les articulations d'une main", fontsize=15)
plt.show()
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment