Images and matrices

Cheat sheet how to converge image into arrays and the other way around.

In [1]:
from jyquickhelper import add_notebook_menu
add_notebook_menu()
Out[1]:
run previous cell, wait for 2 seconds

PIL: simple operations

Open

In [2]:
from PIL import Image
img = Image.open("images1.jpg")
img
Out[2]:
In [3]:
img.size
Out[3]:
(289, 175)
In [4]:
img.resize((50, 50))
Out[4]:

Combine

In [5]:
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
Out[5]:
In [6]:
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)
Out[6]:
In [7]:
combine(img, img, vert=True)
Out[7]: