.. _td1asobelrst: ========================= 1A.algo - filtre de Sobel ========================= .. only:: html **Links:** :download:`notebook `, :downloadlink:`html `, :download:`python `, :downloadlink:`slides `, :githublink:`GitHub|_doc/notebooks/td1a_algo/td1a_sobel.ipynb|*` Le filtre de `Sobel `__ est utilisé pour calculer des gradients dans une image. L’image ainsi filtrée révèle les forts contrastes. .. code:: ipython3 from jyquickhelper import add_notebook_menu add_notebook_menu() .. contents:: :local: Exercice 1 : application d’un filtre ------------------------------------ Le filtre de `Sobel `__ est un filtre qu’on applique à une image pour calculer le gradient d’une image afin de déterminer les contours qui s’y trouve. Le filtre de `Canny `__ permet de flouter une image. Dans un premier temps, on cherchera à appliquer un filtre 3x3 : :math:`\left( \begin{array}{ccc} 1&1&1 \\ 1&1&1 \\ 1&1&1 \end{array} \right)` Qu’on applique au voisinage 3x3 du pixel :math:`p_5` : :math:`\left( \begin{array}{ccc} p_1&p_2&p_3 \\ p_4&p_5&p_6 \\ p_7&p_8&p_9 \end{array} \right)` Après l’application du filtre à ce pixel, le résultat devient : :math:`\left( \begin{array}{ccc} ?&?&? \\ ?& \sum_{i=1}^9 p_i &? \\ ?&?&? \end{array} \right)` On veut maintenant appliquer ce filtre sur l’image suivante : .. code:: ipython3 from pyquickhelper.loghelper import noLOG from pyensae.datasource import download_data f = download_data("python.png", url="http://imgs.xkcd.com/comics/") from IPython.display import Image Image("python.png") .. image:: td1a_sobel_3_0.png Mais avant de pouvoir faire des calculs dessus, il faut pouvoir convertir l’image en un tableau ``numpy`` avec la fonction `numpy.asarray `__. .. code:: ipython3 import PIL import PIL.Image im = PIL.Image.open("python.png") from PIL.ImageDraw import Draw import numpy tab = numpy.asarray(im).copy() tab.flags.writeable = True # afin de pouvoir modifier l'image "dimension",tab.shape, " type", type(tab[0,0]) .. parsed-literal:: ('dimension', (588, 518), ' type', numpy.uint8) Une fois les calculs effectués, il faut convertir le tableau ``numpy`` en image. On peut par exemple blanchir tout une partie de l’image et l’afficher. .. code:: ipython3 tab[100:300,200:400] = 255 im2 = PIL.Image.fromarray(numpy.uint8(tab)) im2.save("python_white.png") Image("python_white.png") .. image:: td1a_sobel_7_0.png Et maintenant, il s’agit d’appliquer le filtre de Canny uniforme présenté ci-dessus et d’afficher l’image, soit en utilisant ``numpy``, soit sans ``numpy`` en convertissant l’image en liste avec la méthode `tolist `__. On pourra comparer les temps de calcul. .. code:: ipython3 l = tab.tolist() len(l),len(l[0]) .. parsed-literal:: (588, 518)