import matplotlib.pyplot as plt
from skimage import data
# Charger l'image de test depuis skimage
image = data.chelsea()
# Afficher l'image
plt.figure(figsize = (4,3))
plt.imshow(image)
plt.axis("off") # Supprimer les axes pour une meilleure lisibilité
plt.title("Image d'exemple (skimage)")
plt.show()
# Analyse de l'objet image
print(type(image))
print(image.shape)
<class 'numpy.ndarray'>
(300, 451, 3)
# Créer une copie pour ne pas modifier l'original
image_no_red = image.copy()
# On enlève la composante Rouge ( RGB )
image_no_red[:, :, 0] = 0
plt.figure(figsize = (8,3))
plt.subplot(1,2,1) # 2 ligne 1 colonne, position 1
plt.axis("off")
plt.imshow(image)
plt.subplot(1,2,2) # 2 ligne 1 colonne, position 2
plt.axis("off")
plt.imshow(image_no_red)
plt.show()
# Repérer une couleur dans une image
import cv2 #
import numpy as np
import matplotlib.pyplot as plt
# Charger l'image (format BGR par défaut dans OpenCV)
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
# Convertir l'image en espace de couleur HSV
hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# Définir la plage de couleurs à détecter (par exemple, rouge)
lower_hsv = np.array([20, 100, 100]) # Limite inférieure (Hue, Saturation, Value)
upper_hsv = np.array([50, 255, 255]) # Limite supérieure (Hue, Saturation, Value)
# Créer un masque binaire correspondant à la plage de couleurs
mask = cv2.inRange(hsv_image, lower_hsv, upper_hsv)
# Appliquer le masque à l'image originale
result = cv2.bitwise_and(image, image, mask=mask)
# Convertir les images BGR en RGB pour l'affichage avec Matplotlib
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
result_rgb = cv2.cvtColor(result, cv2.COLOR_BGR2RGB)
# Afficher les images originale, masque et résultat
plt.figure(figsize=(8, 3))
plt.subplot(1, 3, 1)
plt.imshow(image_rgb)
plt.title("Image originale")
plt.axis("off")
plt.subplot(1, 3, 2)
plt.imshow(mask, cmap="gray")
plt.title("Masque")
plt.axis("off")
plt.subplot(1, 3, 3)
plt.imshow(result_rgb)
plt.title("Couleur repérée")
plt.axis("off")
plt.tight_layout()
plt.show()
# récupération d'un pixel
pixel = image_rgb[0,0,2]
print(pixel)
# modification d'un pixel
image_rgb[0,0,2] = 50
image_rgb[0,0] = (56, 120, 120)
120
# Je change la couleur des yeux
# Remplacer tous les pixels non noirs par rouge (255, 0, 0)
#result_rgb[np.any(result_rgb != [0, 0, 0], axis=-1)] = [255, 0, 0]
mask = ( result_rgb[:,:] != (0, 0, 0) )
#print(mask)
print(result_rgb.shape)
print(image_rgb.shape)
#result_rgb[mask] = 255 # met 255 sur les 3 pixels
result_rgb[np.any(mask, axis=-1)] = [255, 0, 0]
image_rgb[np.any(mask, axis=-1)] = [255, 0, 0]
plt.figure(figsize=(6, 3))
plt.subplot(1, 2, 1)
plt.imshow(result_rgb)
plt.title("Couleur repérée")
plt.axis("off")
plt.subplot(1, 2, 2)
plt.imshow(image_rgb)
plt.title("Image originale")
plt.axis("off")
plt.tight_layout()
plt.show()
(300, 451, 3)
(300, 451, 3)