python中的Pillow常用功能詳解
Pillow 的常用功能
Pillow 是一個強大的圖像處理庫,提供了豐富的功能來處理和操作圖像。以下是一些常用的功能及其示例代碼:
1. 打開和保存圖像
Pillow 可以輕松地打開和保存各種格式的圖像文件。
示例代碼
from PIL import Image
# 打開圖像
img = Image.open("example.jpg")
# 顯示圖像
img.show()
# 保存圖像
img.save("output.jpg")2. 裁剪圖像
裁剪圖像的特定區(qū)域。
示例代碼
Python復(fù)制
from PIL import Image
# 打開圖像
img = Image.open("example.jpg")
# 裁剪圖像(左上角坐標(biāo),右下角坐標(biāo))
cropped_img = img.crop((50, 50, 200, 200))
# 顯示裁剪后的圖像
cropped_img.show()3. 調(diào)整圖像大小
調(diào)整圖像的大小。
示例代碼
from PIL import Image
# 打開圖像
img = Image.open("example.jpg")
# 調(diào)整圖像大小
resized_img = img.resize((300, 300))
# 顯示調(diào)整大小后的圖像
resized_img.show()4. 旋轉(zhuǎn)圖像
旋轉(zhuǎn)圖像。
示例代碼
from PIL import Image
# 打開圖像
img = Image.open("example.jpg")
# 旋轉(zhuǎn)圖像
rotated_img = img.rotate(90)
# 顯示旋轉(zhuǎn)后的圖像
rotated_img.show()5. 翻轉(zhuǎn)圖像
水平或垂直翻轉(zhuǎn)圖像。
示例代碼
from PIL import Image
# 打開圖像
img = Image.open("example.jpg")
# 水平翻轉(zhuǎn)
flipped_img = img.transpose(Image.FLIP_LEFT_RIGHT)
# 顯示翻轉(zhuǎn)后的圖像
flipped_img.show()6. 圖像過濾
應(yīng)用各種濾鏡,如模糊、銳化等。
示例代碼
from PIL import Image, ImageFilter
# 打開圖像
img = Image.open("example.jpg")
# 應(yīng)用模糊濾鏡
blurred_img = img.filter(ImageFilter.BLUR)
# 顯示模糊后的圖像
blurred_img.show()7. 圖像合成
將多個圖像合成在一起。
示例代碼
from PIL import Image
# 打開兩個圖像
img1 = Image.open("example1.jpg")
img2 = Image.open("example2.jpg")
# 調(diào)整圖像大小以匹配
img2 = img2.resize(img1.size)
# 合成圖像
combined_img = Image.blend(img1, img2, alpha=0.5)
# 顯示合成后的圖像
combined_img.show()8. 添加文字
在圖像上添加文字。
示例代碼
from PIL import Image, ImageDraw, ImageFont
# 打開圖像
img = Image.open("example.jpg")
# 創(chuàng)建一個繪圖對象
draw = ImageDraw.Draw(img)
# 指定字體和大小
font = ImageFont.truetype("arial.ttf", 36)
# 在圖像上添加文字
draw.text((50, 50), "Hello, Pillow!", font=font, fill=(255, 0, 0))
# 顯示圖像
img.show()9. 調(diào)整圖像模式
將圖像轉(zhuǎn)換為不同的模式,如灰度、RGB 等。
示例代碼
from PIL import Image
# 打開圖像
img = Image.open("example.jpg")
# 轉(zhuǎn)換為灰度圖像
gray_img = img.convert("L")
# 顯示灰度圖像
gray_img.show()10. 創(chuàng)建縮略圖
生成圖像的縮略圖。
示例代碼
from PIL import Image
# 打開圖像
img = Image.open("example.jpg")
# 創(chuàng)建縮略圖
img.thumbnail((128, 128))
# 顯示縮略圖
img.show()Pillow 提供了豐富的功能,用于處理和操作圖像。通過上述示例代碼,你可以輕松地實現(xiàn)圖像的打開、保存、裁剪、調(diào)整大小、旋轉(zhuǎn)、翻轉(zhuǎn)、過濾、合成、添加文字、調(diào)整模式和創(chuàng)建縮略圖等操作。希望這些功能和示例代碼能幫助你更好地使用 Pillow 進行圖像處理。
到此這篇關(guān)于python中的Pillow 有哪些常用的功能?的文章就介紹到這了,更多相關(guān)python Pillow 功能內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
利用Python批量提取Win10鎖屏壁紙實戰(zhàn)教程
這篇文章主要給大家介紹了關(guān)于利用Python批量提取Win10鎖屏壁紙的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2018-03-03
Python 實現(xiàn)將numpy中的nan和inf,nan替換成對應(yīng)的均值
這篇文章主要介紹了Python 實現(xiàn)將numpy中的nan和inf,nan替換成對應(yīng)的均值,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06

