Table Of Contents
Table Of Contents

Images and matrices

Links: notebook, chsh_images2html.html, PDF, python, chsh_images.slides.html, chsh_images.slides2p.html, GitHub

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

from jyquickhelper import add_notebook_menu
add_notebook_menu()

PIL: simple operations

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

Combine

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

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

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')

more simple way

array = numpy.array(img)
array.shape
(175, 289, 3)

Array to array transposed

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

Array to PIL

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

Split colors

im_r, im_b, im_g = img.split()
combine(im_r, im_b, im_g, mode="L")
../_images/chsh_images_21_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_25_0.png

Zoom

img2.resize((720, 120))
../_images/chsh_images_27_0.png