在python中進行圖像處理,咱們有三個好工具:OpenCV, SciKit-Image 和 Pillow。可是在本文中,爲了理解一些簡單圖像處理技術的基礎,咱們將使用numpy。因此這也是練習numpy的良好教程。python
Python Imaging Library (PIL)是python下的圖像處理模塊,支持多種格式,並提供強大的圖形與圖像處理功能。Python3.x中須要先安裝:數組
pip install pillow
from PIL import Image im = Image.open("pubu.jpg") im.show()
import numpy as np imgs = np.array(im) imgs.shape
(711, 400, 3)
imgs[:2,:2,:]
array([[[27, 43, 33], [22, 35, 26]], [[28, 45, 37], [27, 42, 35]]], dtype=uint8)
分離通道將每一個像素點中RGB三色中的其餘兩位分別置位0。單像素單通道的值是0~255之間的整數,故而這裏使用uint8工具
tmpr = np.zeros(imgs.shape,dtype='uint8') tmpr[:,:,0]=imgs[:,:,0] print(tmpr[:2,:2,:]) tmpr_im = Image.fromarray(tmpr) tmpr_im.show()
[[[27 0 0] [22 0 0]] [[28 0 0] [27 0 0]]]
tmpg = np.zeros(imgs.shape,dtype='uint8') tmpg[:,:,1]=imgs[:,:,1] tmpg_im = Image.fromarray(tmpg) tmpg_im.show()
tmpb = np.zeros(imgs.shape,dtype='uint8') tmpb[:,:,2]=imgs[:,:,2] tmpb_im = Image.fromarray(tmpb) tmpb_im.show()
彩色圖像轉換爲灰度圖像時,須要計算圖像中每一個像素有效的亮度值,其計算公式爲: Y = 0.3R + 0.59G + 0.11B。故而,向量[0.3,0.59,0.11]
和三維張量作點積,便可獲得二維張量(矩陣)也就是灰度圖ui
ynp = np.array([0.3,0.59,0.18]) tmph = np.dot(imgs,ynp) tmph_im = Image.fromarray(tmph) tmph_im.show()
轉置能夠對數組進行重置,轉置有三種方式,transpose方法、T屬性以及swapaxes方法。spa
tmpht=tmph.T print(tmph.shape) print(tmpht.shape) tmph_im = Image.fromarray(tmpht) tmph_im.show()
(711, 400) (400, 711)
對於高維數組,transpose須要用到一個由軸編號組成的元組,才能進行轉置。對多維數組來講,肯定最底層的一個基本元素位置須要用到的索引個數便是維度。好比說三維的數組,那就對維度進行編號,也就是0,1,2。這樣說可能比較抽象。這裏的0,1,2能夠理解爲對shape返回元組的索引。3d
transpose進行的操做實際上是將各個維度重置,原來(711,400,3)對應的是(0,1,2)。使用transpose(1,0,2)後,各個維度大小變爲(400,711,3),其實就是將第一維和第二維互換。code
imgs.shape
(711, 400, 3)
imgst=imgs.transpose((1,0,2)) imgst_im = Image.fromarray(imgst) imgst_im.show()
即交換張量的第一維的行順序,對於一維數組來講,python原生的list和numpy的array的切片操做都是相同的。無非是記住一個規則arr_name[start: end: step]
。例如:blog
arr = np.arange(4) arr
array([0, 1, 2, 3])
arr[::-1]
array([3, 2, 1, 0])
imgsp=imgs[::-1] imgsp_im = Image.fromarray(imgsp) imgsp_im.show()
即交換張量的第二維的列順序,相對於一維數組而言,二維(多維)數組用的會更多。通常語法是arr_name[行操做, 列操做]
。例如:教程
arr1 = np.arange(12).reshape(2,6) arr1
array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11]])
arr1[:,::-1]
array([[ 5, 4, 3, 2, 1, 0], [11, 10, 9, 8, 7, 6]])
imgsf=imgs[:,::-1] imgsf_im = Image.fromarray(imgsf) imgsf_im.show()
即交換第三維的R,G,B 三色的列的位置。例如:索引
a = np.array([[1,2,3],[2,3,4],[1,6,5], [9,3,4]]) a
array([[1, 2, 3], [2, 3, 4], [1, 6, 5], [9, 3, 4]])
a1=a[:,[1,0,2]] a1
array([[2, 1, 3], [3, 2, 4], [6, 1, 5], [3, 9, 4]])
imgsrgb=imgs[:,:,[1,0,2]] imgsrgb_im = Image.fromarray(imgsrgb) imgsrgb_im.show()
更多文章,請關注: