# -*- coding: utf-8 -*-
"""
Created on Sat Nov  4 23:48:14 2017

@author: Alain
"""

import matplotlib.pyplot as plt
import matplotlib.image as img


""" Lenna """

lenna = img.imread("lenna.png")
plt.imshow(lenna)
plt.show()

def retourneVerticalement(image):
    nl = len(image) # nombre de lignes
    nc = len(image[0]) # nombre de colonnes
    img = [[[1,1,1] for c in range(nc)] for l in range(nl)] #image blanche de même dimension
    # img = img = [[1 for c in range(nc)] for l in range(nl)] #pour une image en niveaux de gris
    for l in range(nl):
        for c in range(nc):
            pixel = image[l][c]
            img[nl-1-l][c]= pixel
    return img
    
lennaTeteEnBas = retourneVerticalement(lenna)
plt.imshow(lennaTeteEnBas)
plt.show()

def retourneHorizontalement(image):
    nl = len(image) # nombre de lignes
    nc = len(image[0]) # nombre de colonnes
    img = [[[1,1,1] for c in range(nc)] for l in range(nl)] #image blanche de même dimension
    # img = img = [[1 for c in range(nc)] for l in range(nl)] #pour une image en niveaux de gris
    for l in range(nl):
        for c in range(nc):
            pixel = image[l][c]
            img[l][nc-1- c]= pixel
    return img

lennaTeteAGauche = retourneHorizontalement(lenna)
plt.imshow(lennaTeteAGauche)
plt.show()    

def gris(image):
    nl = len(image)
    nc = len(image[0])
    img = [[1 for c in range(nc)] for l in range(nl)]
    for l in range(nl):
        for c in range(nc):
            pixel = image[l][c]
            #gr = (pixel[0]+pixel[1]+pixel[2])/3
            gr = 0.299*pixel[0]+0.587*pixel[1]+0.114*pixel[2]
            img[l][c]= gr
    return img
    
lennaGris = gris(lenna)

plt.imshow(lennaGris, cmap='gray')
plt.show()

""" seuillage """

def seuil(image,limite):
    nl = len(image)
    nc = len(image[0])
    img = [[1 for c in range(nc)] for l in range(nl)]
    for l in range(nl):
        for c in range(nc):
            pixel = image[l][c]
            if pixel < limite  :
                img[l][c]= 0
            else:
                img[l][c] = 1
    return img
    
lennaSeuil = seuil(lennaGris,0.5)

plt.imshow(lennaSeuil, cmap='gray')
plt.show()


""" convolution """

lissage = [[1/9,1/9,1/9],[1/9,1/9,1/9],[1/9,1/9,1/9]]
accentuation = [[0,-0.5,0],[-0.5,3,-0.5],[0,-0.5,0]]
embossage=[[-2,-1,0],[-1,0,1],[0,1,2]]
rehausseur = [[-1/6, -2/3, -1/6],[-2/3, 13/3, -2.3],[-1/6, -2/3, -1/6]]

def convolutionGris(image, filtre3x3):
    nl = len(image)
    nc = len(image[0])
    img = [[image[l][c] for c in range(nc)] for l in range(nl)]
    for l in range(1,nl-1):
        for c in range(1,nc-1):
            f = 0
            for i in range(3):
                for j in range(3):
                    f = f + image[l-1+i][c-1+j]*filtre3x3[i][j]
            if f < 0 : 
                f = 0
            elif f > 1 : 
                f = 1
            img[l][c]=f
    return img
    
lennaFiltre = convolutionGris(lennaGris,accentuation)
plt.imshow(lennaFiltre, cmap='gray')
plt.show()

