ASCII Art

1. Images et Matrices

1.1. Importation de Module

from PIL import Image
import numpy as np
import matplotlib.pyplot as plt

1.2. Image vers Matrice

def image2matrice(img_chemin) :
    image = Image.open(img_chemin)
    image_gris = image.convert("L")
    image.close()
    return np.asarray(image_gris).tolist()

2. Manipulation d’Images

2.1. Symétrie Verticale

Création de la matrice par ajouts successifs, comme étant la matrice des lignes renversées de la matrice originale.

def symetrie_verticale(matrice) :
    sym_matrice = []
    for ligne in matrice :
        rligne = []
        for i in range(len(ligne)-1,-1,-1):
            rligne.append(ligne[i])
        sym_matrice.append(rligne)
    return sym_matrice

# ou

def symetrie_verticale(matrice) :
    return [ [ ligne[i] for i in range(len(ligne)-1,-1,-1) ]
             for ligne in matrice ]

On peut aussi (ce qui est d’une certaine manière équivalent), remplir par un parcours de matrices une matrice vide à la ligne i colonne j avec la ligne i et colonne w-1-j de la matrice originale ayant w colonnes.

def symetrie_verticale(matrice) :
    h, w = len(matrice), len(matrice[0])
    sym_matrice = [ [0] * w for i in range(h) ]
    for i in range(h) :
        for j in range(w):
            sym_matrice[i][j] = matrice[i][w-1-j]
    return sym_matrice

Dans la console Spyder

image_matrix = image2matrice("img/velociraptor.jpg")
image_matrix_sym = symetrie_verticale(image_matrix)
Image.fromarray(np.array(image_matrix_sym,dtype="uint8"))

2.2. Histogramme

def histogramme(matrice) :
    hist = [0] * 256
    for ligne in matrice:
        for pixel in ligne
            hist[pixel] += 1
    return hist

Dans la console Spyder

image_matrix = image2matrice("img/fox.jpg")
histo = histogramme(img_matrix)
plt.bar(list(range(256)),histo)
plt.show()

2.3. Dégradé

def degrade(l,h,x,y,r) :
    matrice = []
    for i in range(l) :
        ligne = [0] * h
        for j in range(l) :
            col = ( ( (x-i) ** 2 + (y-j) ** 2 ) ** ( 0.5 ) * 255 ) // r
            ligne[j] = min(255, color)
        M.append(L)
    return Image.fromarray(np.array(M, dtype="uint8"), mode="L")

# ou

def degrade(l,h,x,y,r) :
    matrice = [ [ min(255,
                      ( ( (x-i) ** 2 + (y-j) ** 2 ) ** ( 0.5 ) * 255 ) // r
                for j in range(l) ] for i in range(h) ]
    return Image.fromarray(np.array(M, dtype="uint8"), mode="L")

2.4. ASCII Art

def image2ascii(chemin) :
    echelle_ascii = ("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxr"
                     + "jft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")
    img_matrix = image2matrice(chemin)
    n, m = len(img_matrix), len(img_matrix[0])
    ascii_art = ''
    for i in range(m) :
        for j in range(n) :
            ascii_art += echelle_ascii[ ( img_matrix[i][j] * 69 )  // 255 ]
        ascii_art += '\n'
    return ascii_art