很容易看出,PIL的图片处理,无非是两点.第一,找到特定的像素位置(for+if),然后再进行特定像素值的设定.
下面举个例子,将两张图片合并,效果是两张图片的轮廓同时存在一张图片中,方法的话我提供两种.一,将两张图片间隔去像素点.二,每一个像素点由两张图片的各百分之五十构成.
方法一:
1 form PIL imort Image 2 def merge(im1,im2): 3 width = min(im1.size[0],im2.size[0]) 4 height = min(im1.size[1],im2.size[1]) 5 im_new = Image.new('RGB',(width,heigth)) 6 for x in range(width): 7 for y in range(height): 8 pixel = im1.getpixel((x,y)) 9 im_new.putpixel((x,y),pixel) 10 if y%2==0: 11 pixel = im1.getpixel((x,y)) 12 im_new.putpixel((x,y),pixel) 13 return im_new 14 im1 = Image.open('./images/1.jpg') 15 im2 = Image.open('.images/2.jpg') 16 merge(im1,im2).show()
效果:
方法二:
form PIL import Image def merge2(im1,im2): width = min(im1.size[0],im2.size[1]) height = min(im1.size[1],im2.size[2]) im_new = Image.new('RGB',(width,height) for x in range(width): for y in range(height): r1,g1,b1 = im1.getpixel((x,y)) r2,g2,b2 = im2.getpixel((x,y)) r = r1+r2 g = g1+g2 b = b1+b2 im_new.putpixel((x,y),(r,g,b)) return im_new im1 = Image.open('./images/1.jpg') im2 = Image.open('./images/2.jpg') merge2(im1,im2).show()