Python - Canny lib

Script en Python pour donner un effet “Canny” à vos images en ajouter une couche de vert (mais en conservant les blancs) :

from PIL import Image, ImageOps
import cv2
import numpy as np
import os
import glob

def canny_edge_detection(input_path, output_path):
try:
image = cv2.imread(input_path, cv2.IMREAD_GRAYSCALE)
edges = cv2.Canny(image, 150, 250)
cv2.imwrite(output_path, edges)
print(f"canny_edge_detection : {input_path} - OK")
except Exception as e:
print(f"Erreur lors de la détection des bords de {input_path} : {str(e)}")

def make_green(input_path, output_path):
try:
canny_image = Image.open(input_path).convert("RGB")
canny_array = np.array(canny_image)
white_pixels = np.all(canny_array == [255, 255, 255], axis=-1) # Vérifie si le pixel est blanc

# Remplace les pixels blancs par du vert
canny_array[white_pixels] = [0, 255, 0]

green_image = Image.fromarray(canny_array)
green_image.save(output_path)
print(f"make_green : {input_path} - OK")
except Exception as e:
print(f"Erreur lors de la création de l'image verte pour {input_path} : {str(e)}")

def process_images(directory):
for MonImage_path in glob.glob(os.path.join(directory, "MonImage.jpg")):
canny_output_path = MonImage_path.replace("MonImage.jpg", "canny_output.jpg")
green_output_path = MonImage_path.replace("MonImage.jpg", "MonImage_CANNY.jpg")

canny_edge_detection(MonImage_path, canny_output_path)
make_green(canny_output_path, green_output_path)

if __name__ == "__main__":
base_directory = "MyDIR/"
for dirpath, dirnames, filenames in os.walk(base_directory):
if "MonImage.jpg" in filenames:
process_images(dirpath)

print("--- END ---")

Exemples



Documentation

Internet

> Partager <