- 案例目的
 
本案例通过使用Python图像处理库Pillow,帮助读者进一步了解Python的基本概念:模块、对象、方法和函数的使用。使用Python语言解决实际问题时,往往需要使用由第三方开发的开源Python软件库。
- 案例内容
 
本案例使用图像处理库Pillow中的模块、对象来处理图像:实现读取图像、获取图像信息、调整图像大小、旋转图像、平滑图像、剪切图像等基本图像处理任务。
- 实验环境
 
Pycharm、Anaconda
- 案例研究
 
3.1 安装Pillow
新建Project:work1,在Pycharm中设置File->Settings->Project->Python Interpreter中添加Pillow库。

图 1 添加Pillow库
3.2读取图像与获取图像信息
主要代码:
- # 作者:朱龙强
 - # 时间:2022-3-13
 - # 题目信息:Pilllow库实现图像处理基本任务
 - import PIL
 - from PIL import Image
 - im = PIL.Image.open("C:/Users/JohnRothan/Desktop/girl.jpg")
 - im.show() #打开图像
 - print(im.format, im.size, im.mode) #显示图像格式、大小、模式
 
测试结果:

图 2 打开图像
JPEG (4032, 2714) RGB
3.3 图像基本处理
主要代码:
- import sys
 - import os
 - import PIL.Image
 - import PIL.ImageFilter
 - im = PIL.Image.open("C:\\Users\\JohnRothan\\Desktop\\log.png")
 - width,height = im.size
 - #创建新图像,大小为原始图像的4倍
 - res = PIL.Image.new (im.mode,(2*width,2*height))
 - #把原始图像放置在左上角
 - res. paste(im,(0,0,width,height))
 - #把轮廓过滤CONTOUR的图像放置在右上角
 - contour = im.filter(PIL.ImageFilter.CONTOUR)
 - res.paste(contour,(width,0,2*width,height))
 - #把浮雕过滤EMBOSS的图像放置在左下角
 - emboss = im.filter(PIL.ImageFilter.EMBOSS)
 - res.paste(emboss,(0,height,width,2*height))
 - #把边缘过滤FIND_EDGES的图像放置在右下角
 - edges = im.filter(PIL.ImageFilter.FIND_EDGES)
 - res.paste(edges,(width,height,2*width,2*height))#显示结果图像
 - res.show()
 
测试结果:

图 3 图像基本处理
3.3 调整图像大小
主要代码:
- import PIL.Image
 - im = PIL.Image.open("C:/Users/JohnRothan/Desktop/girl.jpg")
 - img_size_width = int(500)
 - img_size_height = int(400)
 - im_out = im. resize((img_size_width, img_size_height))
 - im_out.show()
 
测试结果:

图 4 图像尺寸变换
3.4 添加图片水印
主要代码:
- from PIL import Image,ImageDraw,ImageFont
 - im = Image.open("C:/Users/JohnRothan/Desktop/girl.jpg")
 - im_log = Image.open("C:/Users/JohnRothan/Desktop/log.png")
 - im_mark = Image.new('RGBA', im.size)
 - im_mark.paste(im_log,(0,0))
 - im_out = Image.composite(im_mark,im, im_mark)
 - im_out.show()
 
测试结果:

图 5 添加图片水印(左上角)
3.5 图片格式批量转换
主要代码:
- import sys
 - import glob
 - import os
 - import PIL.Image
 - img_path = "C:/Users/JohnRothan/Desktop/img" + "/*." + "png"
 - for infile in glob.glob(img_path):
 - f, e = os.path.splitext(infile)
 - outfile = f + "." + "jpg"
 - PIL.Image.open(infile).save(outfile)
 
测试结果:
将img文件下的.png文件转换为.jpg文件










