สวัสดีผู้อ่านทุกท่านครับ บทความนี้ผมจะพาผู้อ่านไปรู้จักกับโมดูล Pillow ซึ่งเป็นด้าน image processing and graphics capabilities หรือโมดูลจัดการและประมวลผลรูปภาพบน Python
ใน Python มีโมดูลด้านนี้ที่ชื่อว่า Python Imaging Library (PIL) ซึ่งรองรับแต่ Python 2 ในเวลานี้ครับ จึงมีคนได้ Fork PIL มาพัฒนาเป็นโมดูล Pillow ครับ รองรับทั้ง Python 2 และ Python 3 เหตุผลที่ Fork ทางนักพัฒนาได้บอกว่า PIL ไม่สนับสนุน setuptools และมีกำหนดการออกเวชั่นใหม่สองปีหรือมากกว่านั้น
โมดูล Pillow ทำอะไรได้บ้าง
- จัดเก็บรูปภาพ (Image Archives)
- แสดงรูปภาพ (Image Display)
- ประมวลผลรูปภาพ (Image Processing) เช่น ปรับขนาดรูปภาพ แปลงไฟล์รูปภาพ ใส่ตัวอักษรลงในภาพ และอื่น ๆ เป็นต้น
ใช้ pip ติดตั้งโดยใช้คำสั่ง
pip install Pillowสำหรับบน Windows โหลดไฟล์ติดตั้งได้ที่ PyPI
ลองจัดการและประมวลผลรูปภาพกราฟิกใน Python ด้วย Pillow
>>> from PIL import Image
>>> im = Image.open("60_1.jpg")
>>> print(im.format, im.size, im.mode)
JPEG (450, 346) RGB
>>> im.show()
ผลลัพธ์
ลองมาปรับขนาดรูปภาพใน Python ด้วย Pillow กัน
>>> out = im.resize((128, 128)) >>> out.show()
ผลลัพธ์
ใส่ข้อความลงในรูปภาพบน Python ด้วย Pillow
ไฟล์ 60_1.jpg

from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
img = Image.open("60_1.jpg") #ดึงรูปภาพเข้ามา
draw = ImageDraw.Draw(img)
#ดึงไฟล์ Font เข้ามาและกำหนดขนาด
font = ImageFont.truetype("CSPraKasFD.otf", 50)
#ใส่ข้อความ โดยมีรูปแบบการใช้งานดังนี้ draw.text((x, y),"Sample Text",(r,g,b))
draw.text((10, 10), "Hello!",font=font)
#บันทึกรูปภาพเป็น sample-out.jpg
img.save('sample-out.jpg')
ผลลัพธ์ไฟล์ sample-out.jpg


หน้าเว็บโครงการ Pillow http://python-pillow.github.io/
เอกสารการใช้งาน Pillow http://pillow.readthedocs.org/
ติดตามบทความต่อไปนะครับ
ขอบคุณครับ

0 ความคิดเห็น:
แสดงความคิดเห็น
แสดงความคิดเห็นได้ครับ :)