Images et matrices#

Links: notebook, html, PDF, python, slides, GitHub

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.

from jyquickhelper import add_notebook_menu
add_notebook_menu()

PIL : operations simples#

Open#

from PIL import Image
img = Image.open("images1.jpg")
img
../_images/chsh_images_4_0.png
img.size
(289, 175)
img.resize((50, 50))
../_images/chsh_images_6_0.png

Combiner#

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
../_images/chsh_images_8_0.png
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)
../_images/chsh_images_9_0.png
combine(img, img, vert=True)
../_images/chsh_images_10_0.png

PIL to array#

Une image en couleur contient trois images, une pour chaque couleur primaire.

import numpy
array = numpy.array(img.getdata(), dtype=numpy.uint8).reshape(img.size[1], img.size[0], 3)
array.shape
(175, 289, 3)
array.dtype
dtype('uint8')

D’une matrice à sa transposée#

array.transpose((2, 1, 0)).shape
(3, 289, 175)

Matrice à PIL#

from PIL import Image
img2 = Image.fromarray(array)
img2
../_images/chsh_images_17_0.png

Séparer les couleurs#

im_r, im_b, im_g = img.split()
combine(im_r, im_b, im_g, mode="L")
../_images/chsh_images_19_0.png

YCbCr#

img_ycbcr = img.convert('YCbCr')
img_ycbcr.size
(289, 175)
img_y, img_cb, img_cr = img_ycbcr.split()
img_y.size
(289, 175)
combine(img_y, img_cb, img_cr, mode="L")
../_images/chsh_images_23_0.png