天天看點

【Python學習】 - PIL - 各種圖像操作

官方文檔:​​http://effbot.org/imagingbook/image.htm​​

1.打開圖像并顯示(注意這樣show的話,會生成本地檔案的):

img=Image.open('1.jpg')

img.show()      

2.轉8位灰階圖

greyimg=img.convert('L')
greyimg.show()      

3.擷取圖檔某一像素點的 (R,G,B)值

from PIL import Image  
  
imagepath='1.jpg'  
img = Image.open(imagepath)  
if img.mode not in ('L', 'RGB'):  
    img = img.convert('RGB')  
r, g, b = img.getpixel((10, 10))      

4.從圖像中随機截取一部分

crop() : 從圖像中提取出某個矩形大小的圖像。它接收一個四元素的元組作為參數,各元素為(left, upper, right, lower),坐标系統的原點(0, 0)是左上角。

leftupx=random.randint(0,img.size[0]-64-1)
leftupy= random.randint(0,img.size[1]-128-1)
img1=img.crop((leftupx,leftupy,leftupx+64,leftupy+128))      

5.儲存圖像

im.save("2.jpg")      

6.PIL中的Image和numpy中的數組array互相轉換

image轉換成array

img=np.array(image)      

array轉換成image

注意img必須強轉成uint8類型!如果是uint16的矩陣而不轉為uint8的話,Image.fromarray這句會報錯

from PIL import Image

im_arr = Image.fromarray(np.uint8(img))      

7.修改圖像大小

im.resize(size, filter) ⇒ image

傳回圖像的調整大小的副本。size參數以像素為機關給出請求的大小,作為2元組:(寬、高)。

The filter argument can be one of NEAREST (use nearest neighbour), BILINEAR (linear interpolation in a 2x2 environment), BICUBIC (cubic spline interpolation in a 4x4 environment), or ANTIALIAS (a high-quality downsampling filter). If omitted, or if the image has mode “1” or “P”, it is set to NEAREST.

濾波器參數可以是最接近的(使用最近鄰)、雙線性(在2x2環境中進行線性插值)、雙三次樣條(在4x4環境中進行三次樣條插值)或反鋸齒(高品質的下采樣濾波器)。如果省略,或者圖像模式為“1”或“P”,則将其設定為最接近的模式。

Note that the bilinear and bicubic filters in the current version of PIL are not well-suited for large downsampling ratios (e.g. when creating thumbnails). You should use ANTIALIAS unless speed is much more important than quality.

請注意,目前版本的公益訴訟的雙線性和雙三次濾波器不适用于大的下采樣率(例如,建立縮略圖時)。除非速度比品質更重要,否則應該使用反鋸齒。

(總之一般情況下第二個參數使用預設就好)

比如要将圖檔修改成64*64的
im = im.resize(64,64)      

8.複制圖檔

im = Image.open('1.jpg')

im2 = im.copy()      

9.添加水印,疊加函數,拼接圖像

基于keras中的PIL中的paste()函數可以給圖檔添加水印,也可以疊加函數,拼接圖像,做到多張圖檔結果的可視化。

部分内容選自:​​​​

繼續閱讀