Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การทำงานกับรูปภาพใน Python ด้วย Pillow (PIL)

Pillow เป็นไลบรารี่ยอดนิยมและเป็น Default สำหรับ Image Processing ใน Python เป็นเวอร์ชันอัปเดตของ PIL (Python Image Library) รองรับการจัดการรูปภาพตั้งแต่พื้นฐานถึงขั้นสูง เป็นฐานของ Image Support ใน SciPy และ Matplotlib

ติดตั้ง Pillow

pip install pillow

โหลดและแสดงรูปภาพ

from PIL import Image

# โหลดรูป
img = Image.open('statue_of_unity.jpg')

# รายละเอียดพื้นฐาน
print("Format:", img.format)   # JPEG, PNG, etc.
print("Mode:", img.mode)       # RGB, CMYK, etc.
print("Size:", img.size)       # (width, height)

# แสดงรูป (ใช้ Default Viewer ของ OS)
img.show()

ผลลัพธ์

Format: JPEG
Mode: RGB
Size: (400, 260)

แปลงเป็น Grayscale

from PIL import Image

image = Image.open('statue_of_unity.jpg').convert('L')
image.show()
image.save('statue_of_unity_gs.jpg')

แปลงประเภทไฟล์ (JPEG → PNG)

from PIL import Image

image = Image.open('statue_of_unity.jpg')
image.save('statue_of_unity.png')

ปรับขนาดรูปภาพ (Resize)

from PIL import Image

image = Image.open('statue_of_unity.jpg')
new_image = image.resize((440, 600))
new_image.save('statue_of_unity_440x600.jpg')

หมายเหตุ: Resize จะยืด/อัดรูป ไม่ใช่ Crop หากต้องการ Crop ใช้ image.crop(box)

หมุนรูปภาพ (Rotate)

from PIL import Image

image = Image.open('statue_of_unity.jpg')
image.rotate(45).show()

สร้าง Thumbnails

from PIL import Image
import glob, os

size = (128, 128)
for infile in glob.glob("*.jpg"):
    file, ext = os.path.splitext(infile)
    image = Image.open(infile)
    image.thumbnail(size, Image.Resampling.LANCZOS)  # ใหม่กว่า ANTIALIAS
    image.save(file + ".thumbnail", "JPEG")

เมธอดสำคัญอื่นๆ

  • crop(box): ตัดรูป (box = (left, upper, right, lower))
  • transpose(method): เปลี่ยนทิศทาง (FLIP_LEFT_RIGHT, ROTATE_90, ฯลฯ)
  • filter(filter): ใช้ Filter เช่น BLUR, SHARPEN, EDGE_ENHANCE
  • convert(mode): แปลง Mode เช่น 'L' (Grayscale), 'RGB', 'CMYK', '1' (Binary)