导入 numpy 、PIL
numpy用来做矩阵运算,PIL用来读取图片。
import numpy as np
from PIL import Image
读取图片,然后转换成RGB模式存在矩阵里
im = Image.open(imagename).convert('RGB')
arr = np.array(im)
查看arr的shape,可以看到arr是个3维的数组,数组大小等于 长*宽*3
In [566]: arr.shape
Out[566]: (313, 450, 3)
每个像素有3个数字表示,分别对应(R,G,B)
IN [567]: arr[0][0]
Out[567]: array([6, 4, 9], dtype=uint8)
原始图片
彩色转黑白
把像素的R,G,B三个通道数值都置为r*0.299+g*0.587+b*0.114
def blackWithe(imagename):
# r,g,b = r*0.299+g*0.587+b*0.114
im = np.asarray(Image.open(imagename).convert('RGB'))
trans = np.array([[0.299,0.587,0.114],[0.299,0.587,0.114],[0.299,0.587,0.114]]).transpose()
im = np.dot(im,trans)
return Image.fromarray(np.array(im).astype('uint8'))
流年
把R通道的数值开平方,然后乘以一个参数
def fleeting(imagename,params=12):
im = np.asarray(Image.open(imagename).convert('RGB'))
im1 = np.sqrt(im*[1.0,0.0,0.0])*params
im2 = im*[0.0,1.0,1.0]
im = im1+im2
return Image.fromarray(np.array(im).astype('uint8'))
旧电影
把像素的R,G,B三个通道数值,3个通道的分别乘以3个参数后求和,最后把超过255的值置为255
def oldFilm(imagename):
im = np.asarray(Image.open(imagename).convert('RGB'))
# r=r*0.393+g*0.769+b*0.189 g=r*0.349+g*0.686+b*0.168 b=r*0.272+g*0.534b*0.131
trans = np.array([[0.393,0.769,0.189],[0.349,0.686,0.168],[0.272,0.534,0.131]]).transpose()
# clip 超过255的颜色置为255
im = np.dot(im,trans).clip(max=255)
return Image.fromarray(np.array(im).astype('uint8'))
反色
这个最简单了,用255减去每个通道的原来的数值
def reverse(imagename):
im = 255 - np.asarray(Image.open(imagename).convert('RGB'))
return Image.fromarray(np.array(im).astype('uint8'))
个人公众号