Pillow (fork của PIL) là thư viện xử lý ảnh mặc định cho Python. Hỗ trợ mở, chỉnh sửa, chuyển đổi, lọc, vẽ lên ảnh.
Cài đặt
pip install pillow
Tải và hiển thị ảnh
from PIL import Image
img = Image.open('statue_of_unity.jpg')
print(img.format) # JPEG
print(img.mode) # RGB
print(img.size) # (400, 260)
img.show() # Mở bằng viewer mặc định OS
Chuyển sang grayscale
from PIL import Image
img = Image.open('statue_of_unity.jpg').convert('L') # 'L' = grayscale
img.show()
img.save('statue_of_unity_gs.jpg')
Chuyển đổi định dạng
from PIL import Image
img = Image.open('statue_of_unity.jpg')
img.save('statue_of_unity.png') # Tự động chuyển JPEG -> PNG
Resize (thay đổi kích thước)
from PIL import Image
img = Image.open('statue_of_unity.jpg')
new_img = img.resize((440, 600)) # (width, height)
new_img.save('statue_of_unity_440x600.jpg')
Lưu ý: Resize làm méo tỷ lệ nếu không giữ aspect ratio. Dùng thumbnail() để giữ tỷ lệ.
Crop (cắt ảnh)
# box = (left, upper, right, lower)
cropped = img.crop((50, 50, 200, 200))
cropped.save('cropped.jpg')
Rotate (xoay ảnh)
rotated = img.rotate(45) # độ, ngược chiều kim đồng hồ
rotated.show()
rotated.save('rotated.jpg')
Tạo thumbnail (hình thu nhỏ)
from PIL import Image
import glob, os
size = (128, 128)
for infile in glob.glob("*.jpg"):
file, ext = os.path.splitext(infile)
im = Image.open(infile)
im.thumbnail(size, Image.Resampling.LANCZOS) # Image.ANTIALIAS deprecated
im.save(file + ".thumbnail", "JPEG")
Các mode ảnh phổ biến
| Mode | Mô tả |
|---|---|
| 1 | 1-bit pixels, black and white |
| L | 8-bit grayscale |
| RGB | 3x8-bit true color |
| RGBA | 4x8-bit true color + alpha |
| CMYK | 4x8-bit color separation |
| P | 8-bit palette |
Ứng dụng nâng cao
ImageFilter: Blur, Sharpen, Edge Enhance, Emboss...ImageDraw: Vẽ hình, text lên ảnh.ImageFont: Font cho text.ImageEnhance: Điều chỉnh Brightness, Contrast, Color, Sharpness.ImageChops: Phép toán kênh (add, subtract, multiply...).