用python簡單處理圖片(2):圖像通道\幾何變換\裁剪


一、圖像通道

1、彩色圖像轉灰度圖

from PIL import Image
import matplotlib.pyplot as plt
img=Image.open('d:/ex.jpg')
gray=img.convert('L')
plt.figure("beauty")
plt.imshow(gray,cmap='gray')
plt.axis('off')
plt.show()

使用函數convert()來進行轉換,它是圖像實例對象的一個方法,接受一個 mode 參數,用以指定一種色彩模式,mode 的取值可以是如下幾種:

· 1 (1-bit pixels, black and white, stored with one pixel per byte)
· L (8-bit pixels, black and white)
· P (8-bit pixels, mapped to any other mode using a colour palette)
· RGB (3x8-bit pixels, true colour)
· RGBA (4x8-bit pixels, true colour with transparency mask)
· CMYK (4x8-bit pixels, colour separation)
· YCbCr (3x8-bit pixels, colour video format)
· I (32-bit signed integer pixels)
· F (32-bit floating point pixels)

2、通道分離與合並

from PIL import Image
import matplotlib.pyplot as plt
img=Image.open('d:/ex.jpg')  #打開圖像
gray=img.convert('L')   #轉換成灰度
r,g,b=img.split()   #分離三通道
pic=Image.merge('RGB',(r,g,b)) #合並三通道
plt.figure("beauty")
plt.subplot(2,3,1), plt.title('origin')
plt.imshow(img),plt.axis('off')
plt.subplot(2,3,2), plt.title('gray')
plt.imshow(gray,cmap='gray'),plt.axis('off')
plt.subplot(2,3,3), plt.title('merge')
plt.imshow(pic),plt.axis('off')
plt.subplot(2,3,4), plt.title('r')
plt.imshow(r,cmap='gray'),plt.axis('off')
plt.subplot(2,3,5), plt.title('g')
plt.imshow(g,cmap='gray'),plt.axis('off')
plt.subplot(2,3,6), plt.title('b')
plt.imshow(b,cmap='gray'),plt.axis('off')
plt.show()

二、裁剪圖片

從原圖片中裁剪感興趣區域(roi),裁剪區域由4-tuple決定,該tuple中信息為(left, upper, right, lower)。 Pillow左邊系統的原點(0,0)為圖片的左上角。坐標中的數字單位為像素點。

from PIL import Image
import matplotlib.pyplot as plt
img=Image.open('d:/ex.jpg')  #打開圖像
plt.figure("beauty")
plt.subplot(1,2,1), plt.title('origin')
plt.imshow(img),plt.axis('off')

box=(80,100,260,300)
roi=img.crop(box)
plt.subplot(1,2,2), plt.title('roi')
plt.imshow(roi),plt.axis('off')
plt.show()

用plot繪制顯示出圖片后,將鼠標移動到圖片上,會在右下角出現當前點的坐標,以及像素值。

三、幾何變換 

Image類有resize()、rotate()和transpose()方法進行幾何變換。

 1、圖像的縮放和旋轉

dst = img.resize((128, 128))
dst = img.rotate(45) # 順時針角度表示
2、轉換圖像
dst = im.transpose(Image.FLIP_LEFT_RIGHT) #左右互換
dst = im.transpose(Image.FLIP_TOP_BOTTOM) #上下互換
dst = im.transpose(Image.ROTATE_90)  #順時針旋轉
dst = im.transpose(Image.ROTATE_180)
dst = im.transpose(Image.ROTATE_270)
transpose()和rotate()沒有性能差別。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM