1. 安裝 輸入 pip install PIL報錯: ERROR: Could not find a version that satisfies the requirement PIL (from versions: none) ERROR: No matching distribution f ...
1. 安裝
輸入 pip install PIL報錯:
ERROR: Could not find a version that satisfies the requirement PIL (from versions: none)
ERROR: No
matching distribution found for PIL
解決方案:
Python3中Pillow源自PIL(在2中使用)
(1) python -m pip install Pillow
(2) pip install path\文件名 文件名為在網址:
https://www.lfd.uci.edu/~gohlke/pythonlibs/
中下載對應的模塊。
使用(1)時報錯:
ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out.
超時問題,延長時間:
python -m pip --default-timeout=100 install -U Pillow
註:pillow是PIL(Python成像庫)的一個分支,不再被維護。所以,為了保持向後相容性,往往使用舊的模塊名稱——PIL,即引用模塊,直接使用import PIL
2. 功能
以快速訪問幾種基本像素類型表示的圖像數據為核心,能對圖像做歸檔處理、顯示圖像、常見的圖像處理(變換、點操作、濾波、顏色等等)。
1.1 Image模塊
from PIL import Image
# 打開一個圖像
Picture = Image.open("C:\\Users\\sue\\Pictures\\test.png")
print(Picture)
# 返回圖像實例的屬性
print("圖像格式:{};圖像模式:{};圖像大小:{}。".format(Picture.format,Picture.mode,Picture.size))
# 查看實例,show是暫時存放了一個臨時文件,存在效率問題
Picture.show()
# 實例的方法:
# 1.保存圖片,以及轉換圖片格式,無法轉換報轉換錯誤:svae(存儲文件名[,存儲文件格式:可省略由擴展名決定])
Picture.save("C:\\Users\\sue\\Pictures\\test2.png","PNG")
Picture.save("C:\\Users\\sue\\Pictures\\test3.jpg")
try:
Picture.save("C:\\Users\\sue\\Pictures\\test4.jpg","JPG") #明確格式後,加轉換格式反而報錯KeyError
except:
print("cannot convert")
# 2.製作縮略圖 p.thumbnail((x,y)),參數為一個元組
width,heighth = Picture.size
Picture.thumbnail((width/2,heighth/2))
Picture.save("C:\\Users\\sue\\Pictures\\test2.png","PNG")
# 3.裁剪圖片:p.crop((x,y,x+m,y+n)),x,y為以圖片左上角為原點,向下為y軸,向右為x軸;
# m,n為想要裁剪的長寬
# 在原圖(20,10)的位置開始裁剪一個長為200,寬100的圖
PCrop = Picture.crop((20,40,20+200,10+100))
PCrop.show()
# 4.變形和粘貼
# p.transpose(Image.XX):其中XX=FLIP_LEFT_RIGHT(左右鏡像);FLIP_TOP_BOTTOM(上下鏡像)
# ROTATE_90(逆時針旋轉90度);RATATE_180(逆時針旋轉180度);ROTATAE_270;
# TRANSPOSE(像素矩陣轉置,空間變換);TRANVERSE(空間變換)
# p.paste(p1,(x,y,x+m,y+n)),將圖片p1粘貼到p的(x,y)處,占長m寬n的大小。後面兩個不寫就是完全粘貼p1
from PIL import Image
# 將人物圖像的左邊鏡像顛倒,複製到右邊,右邊原樣複製到左邊
def P_transpose(P):
x,y = P.size
pleft = P.crop((0,0,x//2,y))
pright = P.crop((x//2,0,x,y))
pleft = pleft.transpose(Image.FLIP_TOP_BOTTOM)
P.paste(pright,(0,0,x//2,y))
P.paste(pleft,(x//2,0,x,y))
P.show()
Picture = Image.open("C:\\Users\\sue\\Pictures\\人物.png")
P_transpose(P)
# 5.調整尺寸
# resize((m,n))
# rotate(sigma),逆時針調整角度