在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()
更多文章,请关注: