.. _chshimagesrst: =================== Images and matrices =================== .. only:: html **Links:** :download:`notebook `, :downloadlink:`html `, :download:`PDF `, :download:`python `, :downloadlink:`slides `, :githublink:`GitHub|_doc/notebooks/cheat_sheets/chsh_images.ipynb|*` Cheat sheet how to converge image into arrays and the other way around. .. code:: ipython3 from jyquickhelper import add_notebook_menu add_notebook_menu() .. contents:: :local: PIL: simple operations ---------------------- 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 Combine ~~~~~~~ .. 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 ------------ It is a colored image so we have 3 images into 3, red, blue, green. .. 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') **more simple way** .. code:: ipython3 array = numpy.array(img) array.shape .. parsed-literal:: (175, 289, 3) Array to array transposed ------------------------- .. code:: ipython3 array.transpose((2, 1, 0)).shape .. parsed-literal:: (3, 289, 175) Array to PIL ------------ .. code:: ipython3 from PIL import Image img2 = Image.fromarray(array) img2 .. image:: chsh_images_19_0.png Split colors ------------ .. code:: ipython3 im_r, im_b, im_g = img.split() combine(im_r, im_b, im_g, mode="L") .. image:: chsh_images_21_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_25_0.png Zoom ---- .. code:: ipython3 img2.resize((720, 120)) .. image:: chsh_images_27_0.png