.. _chshimagesrst: ================== Images et matrices ================== .. only:: html **Links:** :download:`notebook `, :downloadlink:`html `, :download:`PDF `, :download:`python `, :downloadlink:`slides `, :githublink:`GitHub|_doc/notebooks/cheat_sheet/chsh_images.ipynb|*` Quelques manipulations d’images avec deux modules `Pillow `__ et `scikit-image `__. Le premier module implémente les entrées sorties et quelques effet spéciaux, le second est pratique quand il faut travailler numériquement avec les images. .. code:: ipython3 from jyquickhelper import add_notebook_menu add_notebook_menu() .. contents:: :local: PIL : operations simples ------------------------ Open ~~~~ .. code:: ipython3 from PIL import Image img = Image.open("images1.jpg") img .. image:: chsh_images_4_0.png .. code:: ipython3 img.size .. parsed-literal:: (289, 175) .. code:: ipython3 img.resize((50, 50)) .. image:: chsh_images_6_0.png Combiner ~~~~~~~~ .. code:: ipython3 new_img = Image.new('RGB', (img.size[0]*2, img.size[1])) new_img.paste(img, (0,0)) new_img.paste(img, (img.size[0],0)) new_img .. image:: chsh_images_8_0.png .. code:: ipython3 def combine(*imgs, mode='RGB', vert=False): if vert: sizesx = [im.size[0] for im in imgs] sizesy = [im.size[1] for im in imgs] new_img = Image.new(mode, (max(sizesx), sum(sizesy))) y = 0 for im in imgs: new_img.paste(im, (0, y)) y += im.size[1] else: sizesx = [im.size[0] for im in imgs] sizesy = [im.size[1] for im in imgs] new_img = Image.new(mode, (sum(sizesx), max(sizesy))) x = 0 for im in imgs: new_img.paste(im, (x, 0)) x += im.size[0] return new_img combine(img, img) .. image:: chsh_images_9_0.png .. code:: ipython3 combine(img, img, vert=True) .. image:: chsh_images_10_0.png PIL to array ------------ Une image en couleur contient trois images, une pour chaque couleur primaire. .. code:: ipython3 import numpy array = numpy.array(img.getdata(), dtype=numpy.uint8).reshape(img.size[1], img.size[0], 3) array.shape .. parsed-literal:: (175, 289, 3) .. code:: ipython3 array.dtype .. parsed-literal:: dtype('uint8') D’une matrice à sa transposée ----------------------------- .. code:: ipython3 array.transpose((2, 1, 0)).shape .. parsed-literal:: (3, 289, 175) Matrice à PIL ------------- .. code:: ipython3 from PIL import Image img2 = Image.fromarray(array) img2 .. image:: chsh_images_17_0.png Séparer les couleurs -------------------- .. code:: ipython3 im_r, im_b, im_g = img.split() combine(im_r, im_b, im_g, mode="L") .. image:: chsh_images_19_0.png YCbCr ~~~~~ .. code:: ipython3 img_ycbcr = img.convert('YCbCr') img_ycbcr.size .. parsed-literal:: (289, 175) .. code:: ipython3 img_y, img_cb, img_cr = img_ycbcr.split() img_y.size .. parsed-literal:: (289, 175) .. code:: ipython3 combine(img_y, img_cb, img_cr, mode="L") .. image:: chsh_images_23_0.png