# Images and matrices#

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

```from jyquickhelper import add_notebook_menu
```

## PIL: simple operations#

### Open#

```from PIL import Image
img = Image.open("images1.jpg")
img
```
```img.size
```
```(289, 175)
```
```img.resize((50, 50))
```

### 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
```
```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)
```
```combine(img, img, vert=True)
```

## 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
```

## Split colors#

```im_r, im_b, im_g = img.split()
combine(im_r, im_b, im_g, mode="L")
```

### 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")
```

## Zoom#

```img2.resize((720, 120))
```