---
###### tags: `Sprout`
---
# Pillow
###### 資訊之芽 2022 北區 py 班
###### 黃千睿
###### Credit : 羅啟帆
---
## Introduction
----
PIL (Python Imaging Library)
PIL 已停止開發 後人持續維護 變成今天的 Pillow
----
## 安裝
```python=
pip install pillow
```
[課程程式碼(及範例圖片)](https://github.com/EnzoHuang0807/Sprout)
---
## 起手式

----
## 開啟圖片
```python=
from PIL import Image
img = Image.open("sample.jpg") #宣告一個Image物件
img.show()
```

----
## 圖片尺寸
圖片是由一個個格子 aka 像素(pixel)構成,
每個格子儲存一個顏色的資訊
```python=
print(img.size) #(1280,720)
```
長 : 1280 pixels
寬 : 720 pixels
----
## 灰階圖片
```python=
img.convert('L')
```

----
## 旋轉圖片
```python=
img.rotate(45) #向左旋轉45度
```

----
## 裁切圖片
```python=
mg.crop((400, 300, 1000, 600)) ##(左界, 上界, 右界, 下界)
```

---
## 深入 pixel
----
## 取得單一 pixel 資訊
```python=
t = img.getpixel((W, H)) #(寬,高)
print(t) #(R, G, B) type -> tuple
```
[More on RGB](https://www.rapidtables.com/web/color/RGB_Color.html)
----
## 改變單一 pixel
```python=
img.putpixel((W, H), (R,G,B))
```
----
## 練習
用此 function 修改圖片的每個像素
```python=
def f(t):
return (tuple([int((i ** 0.5) * 16) for i in t]))
```
---
## 變強了 ?!

----
## 強化對比
```python=
from PIL import ImageEnhance
enhancer = ImageEnhance.Contrast(img)
enhancer.enhance(1).show() #original image
enhancer.enhance(1.5).show() #enhanced
```

----
## 練習
* ##### 強化色彩均衡 (color)
* ##### 強化亮度 (brightness)
* ##### 強化清晰度 (sharpness)
[Reference](https://pillow.readthedocs.io/en/stable/reference/ImageEnhance.html)
---
## 濾鏡 (Filter)
----
## Pillow 提供的 Filter

----
## 模糊
```python=
rom PIL import ImageFilter
img.filter(ImageFilter.BLUR).show()
```

---
## DIY Filter
----

目標:把九宮格的資訊加起來平均
i.e. (17 + 15 + 21 + 20 + 3 + 18 + 15 +12 + 21) // 9 = 15
3 -> 15
----
## Filter 定義

----
## 依照前例 :
* size = (3,3)
* kernel = (1,1,1,1,1,1,1,1,1)
* scale = 9
----
```python=
kernel = (1,1,1,1,1,1,1,1,1)
img.filter(ImageFilter.Kernel((3,3), kernel, 9)).show()
```

----
## 神秘的 filter
```python=
kernel = (-1,-1,-1,-1,8,-1,-1,-1,-1)
img.filter(ImageFilter.Kernel((3,3), kernel, 1)).show()
```

----
## 取九宮格最小值的 filter
```python=
img.filter(ImageFilter.MinFilter)
```

---
## That's ALL !
## 現在是...休息時間
{"metaMigratedAt":"2023-06-17T02:57:25.790Z","metaMigratedFrom":"Content","title":"Pillow","breaks":true,"contributors":"[{\"id\":\"12fd27f5-82a5-4f30-8a85-e747ae0676cf\",\"add\":2958,\"del\":224}]"}