Python PIL图片特效 用Python PIL实现几个简单的图片特效
billlbilll 人气:0导入 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'))
PS:示例
from PIL import Image, ImageFilter # 打开一个jpg图像文件,注意是当前路径: im = Image.open('Penguins.jpg') # 模糊 im2 = im.filter(ImageFilter.BLUR) # 模糊可设置模糊的程度 im22 = im.filter(ImageFilter.BoxBlur(200)) # 轮廓滤波 im3 = im.filter(ImageFilter.CONTOUR) # 边缘增强滤波(锐化) im4 = im.filter(ImageFilter.EDGE_ENHANCE) # 浮雕滤波 im5 = im.filter(ImageFilter.EMBOSS) # 寻找边缘信息的滤波 im6 = im.filter(ImageFilter.FIND_EDGES) im2.save('BLUR.jpg', 'jpeg') im3.save('CONTOUR.jpg', 'jpeg') im4.save('EDGE_ENHANCE.jpg', 'jpeg') im5.save('EMBOSS.jpg', 'jpeg') im6.save('FIND_EDGES.jpg', 'jpeg') im22.save('BoxBlur(200).jpg', 'jpeg')
加载全部内容