1. 程式人生 > 程式設計 >python Pillow影象處理方法彙總

python Pillow影象處理方法彙總

這篇文章主要介紹了python Pillow影象處理方法彙總,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

Pillow中文文件:https://pillow-cn.readthedocs.io/zh_CN/latest/handbook/tutorial.html

安裝:pip install pillow

操作影象:

#!/usr/bin/env python3
# _*_ coding utf-8 _*_

__author__ = 'nxz'

from PIL import Image,ImageFilter
from time import sleep

# 開啟一個jpg影象檔案
im = Image.open('test.jpg')
w,h = im.size #
print('圖片的寬:%s,和高:%s' % (w,h))

# 圖片縮放
im.thumbnail((w // 2,h // 2))
w,h = im.size
print(w,h)

# 縮放之後的圖片重新儲存
im.save('thumbnail.jpg','jpeg')

# 其他功能:切片、旋轉、濾鏡、輸出文字、調色盤

# 模糊效果
im2 = im.filter(ImageFilter.BLUR)
im2.save('blur.jpg','jpeg')

截圖:

from PIL import ImageGrab
from time import sleep

m = int(input("請輸入想截圖多少次:"))
n = 1
while n <= m:
  sleep(0.02)
  im = ImageGrab.grab()
  local = (r'%s.jpg' % (n))
  im.save(local,'jpeg')
  n = n + 1

轉換檔案到JPEG:

'''
將指定路徑下的圖片字尾改為 “.jpg” 格式
'''

from PIL import Image
import os,sys

for infile in sys.argv[1:]:
  f,e = os.path.splitext(infile)
  outfile = f + '.jpg'
  if infile != outfile:
    try:
      Image.open(infile).save(outfile)
    except Exception as exc:
      print(exc)

GIF動圖:

"""
GIf動圖
"""

from PIL import Image

im = Image.open('test.jpg')
images = []
images.append(Image.open('blur.png'))
images.append(Image.open('test.jpg'))
im.save('gif.gif',save_all=True,append_image=images,loop=1,duration=1,comment=b'aaaabbb')

幾何變換:

#簡單的集合變換
out = im.resize((128,128))

#旋轉影象
out = im.transpose(Image.FLIP_LEFT_RIGHT) #翻轉
out = im.transpose(Image.FLIP_TOP_BOTTOM)
out = im.transpose(Image.ROTATE_90)
out = im.transpose(Image.ROTATE_180) #旋轉180°
out = im.transpose(Image.ROTATE_270) #旋轉270°

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。