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]:

PIL to array

It is a colored image so we have 3 images into 3, red, blue, green.

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

more simple way

In [10]:
array = numpy.array(img)
array.shape
Out[10]:
(175, 289, 3)

Array to array transposed

In [11]:
array.transpose((2, 1, 0)).shape
Out[11]:
(3, 289, 175)

Array to PIL

In [12]:
from PIL import Image
img2 = Image.fromarray(array)
img2
Out[12]:

Split colors

In [13]:
im_r, im_b, im_g = img.split()
combine(im_r, im_b, im_g, mode="L")
Out[13]:

YCbCr

In [14]:
img_ycbcr = img.convert('YCbCr')
img_ycbcr.size
Out[14]:
(289, 175)
In [15]:
img_y, img_cb, img_cr = img_ycbcr.split()
img_y.size
Out[15]:
(289, 175)
In [16]:
combine(img_y, img_cb, img_cr, mode="L")
Out[16]:

Zoom

In [17]:
img2.resize((720, 120))
Out[17]:
In [18]: