使用Pillow库处理图像文件

  • 案例目的

本案例通过使用Python图像处理库Pillow,帮助读者进一步了解Python的基本概念:模块、对象、方法和函数的使用。使用Python语言解决实际问题时,往往需要使用由第三方开发的开源Python软件库。

  • 案例内容

本案例使用图像处理库Pillow中的模块、对象来处理图像:实现读取图像、获取图像信息、调整图像大小、旋转图像、平滑图像、剪切图像等基本图像处理任务。

  • 实验环境

Pycharm、Anaconda

  • 案例研究

3.1 安装Pillow

    新建Project:work1,在Pycharm中设置File->Settings->Project->Python Interpreter中添加Pillow库。

1 添加Pillow

3.2读取图像与获取图像信息

主要代码:

  1. 作者:JohnRothan  
  2. 时间:2022-3-13  
  3. 题目信息:Pilllow库实现图像处理基本任务  
  4.   
  5. import PIL  
  6. from PIL import Image  
  7.   
  8. im = PIL.Image.open("C:/Users/JohnRothan/Desktop/girl.jpg")  
  9. im.show()   #打开图像  
  10. print(im.format, im.size, im.mode)  #显示图像格式、大小、模式  

测试结果:

2 打开图像

JPEG (4032, 2714) RGB

3.3 图像基本处理

主要代码:

  1. import sys  
  2. import os  
  3. import PIL.Image  
  4. import PIL.ImageFilter  
  5. im = PIL.Image.open("C:\\Users\\JohnRothan\\Desktop\\log.png")  
  6. width,height = im.size  
  7. #创建新图像,大小为原始图像的4  
  8. res = PIL.Image.new (im.mode,(2*width,2*height))  
  9. #把原始图像放置在左上角  
  10. res. paste(im,(0,0,width,height))  
  11. #把轮廓过滤CONTOUR的图像放置在右上角  
  12. contour = im.filter(PIL.ImageFilter.CONTOUR)  
  13. res.paste(contour,(width,0,2*width,height))  
  14. #把浮雕过滤EMBOSS的图像放置在左下角  
  15. emboss = im.filter(PIL.ImageFilter.EMBOSS)  
  16. res.paste(emboss,(0,height,width,2*height))  
  17. #把边缘过滤FIND_EDGES的图像放置在右下角  
  18. edges = im.filter(PIL.ImageFilter.FIND_EDGES)  
  19. res.paste(edges,(width,height,2*width,2*height))#显示结果图像  
  20. res.show()  

测试结果:

3 图像基本处理

3.3 调整图像大小

主要代码:

  1. import PIL.Image  
  2.   
  3. im = PIL.Image.open("C:/Users/JohnRothan/Desktop/girl.jpg")  
  4. img_size_width = int(500)  
  5. img_size_height = int(400)  
  6. im_out = im. resize((img_size_width, img_size_height)) 
  7. im_out.show() 

测试结果:

4 图像尺寸变换

3.4 添加图片水印

主要代码:

  1. from PIL import Image,ImageDraw,ImageFont  
  2.   
  3. im = Image.open("C:/Users/JohnRothan/Desktop/girl.jpg")  
  4. im_log = Image.open("C:/Users/JohnRothan/Desktop/log.png")  
  5. im_mark = Image.new('RGBA', im.size)  
  6. im_mark.paste(im_log,(0,0))  
  7. im_out = Image.composite(im_mark,im, im_mark)  
  8. im_out.show()  

测试结果:

5 添加图片水印(左上角)

 3.5 图片格式批量转换

主要代码:

  1. import sys  
  2. import glob  
  3. import os  
  4. import PIL.Image  
  5.   
  6. img_path = "C:/Users/JohnRothan/Desktop/img" + "/*." + "png"  
  7. for infile in glob.glob(img_path):  
  8.     f, e = os.path.splitext(infile)  
  9.     outfile = f + "." + "jpg"  
  10.     PIL.Image.open(infile).save(outfile)  

测试结果:

将img文件下的.png文件转换为.jpg文件

  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

哈士奇谭

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值