侯体宗的博客
  • 首页
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

python使用pil进行图像处理(等比例压缩、裁剪)实例代码

Python  /  管理员 发布于 7年前   520

PIL中设计的几个基本概念

1.通道(bands):即使图像的波段数,RGB图像,灰度图像

以RGB图像为例:

>>>from PIL import Image>>>im = Image.open('*.jpg')   # 打开一张RGB图像>>>im_bands = im.getbands() # 获取RGB三个波段>>>len(im_bands)>>>print im_bands[0,1,2]     # 输出RGB三个值

2.模式(mode):定义了图像的类型和像素的位宽。共计9种模式:

>>> im.mode
① 1:1位像素,表示黑和白,但是存储的时候每个像素存储为8bit。② L:8位像素,表示黑和白。③ P:8位像素,使用调色板映射到其他模式。④ RGB:3x8位像素,为真彩色。⑤ RGBA:4x8位像素,有透明通道的真彩色。⑥ CMYK:4x8位像素,颜色分离。⑦ YCbCr:3x8位像素,彩色视频格式。⑧ I:32位整型像素。⑨ F:32位浮点型像素。

3.尺寸(size):获取图像水平和垂直方向上的像素数

>>> im.size()

4.坐标系统(coordinate system):

PIL使用笛卡尔像素坐标系统,坐标(0,0)位于左上角。

注意:坐标值表示像素的角;位于坐标(0,0)处的像素的中心实际上位于(0.5,0.5)。

5.调色板(palette):

调色板模式("P")适用一个颜色调色板为每一个像素定义具体的颜色值。

6.信息(info)

>>> im.info() # 返回值为字典对象

7.滤波器(filters):将多个输入像素映射为一个输出像素的几何操作

PIL提供了4种不同的采样滤波器:

① NEAREST:最近滤波。从输入图像中选取最近的像素作为输出像素。

② BILINEAR:双线性内插滤波。在输入图像的2*2矩阵上进行线性插值。

③ BICUBIC:双立方滤波。在输入图像的4*4矩阵上进行立方插值。

④ ANTIALIAS:平滑滤波。对所有可以影响输出像素的输入像素进行高质量的重采样滤波,以计算输出像素值。

im.resize()和im.thumbnail()用到了滤波器

方法一:resize(size,filter = None)

>>> from PIL import Image >>> im = Image.open('*.jpg')>>> im.size>>> im_resize = im.resize((256,256)) #default 情况下是NEAREST插值方法>>> im_resize0 = im.resize((256,256), Image.BILINEAR)>>> im_resize0.size>>> im_resize1 = im.resize((256,256), Image.BICUBIC)>>> im_resize2 = im.resize((256,256), Image.ANTIALIAS)

方法二:im.thumbnail(size,filter = None)

对于pil的相关介绍就到这里了,下面分享一个使用pil进行图像处理(等比例压缩、裁剪)实例代码,如下:

#coding:utf-8'''  python图片处理  @author:fc_lamp  @blog:http://fc-lamp.blog.163.com/'''import Image as image#等比例压缩图片def resizeImg(**args):  args_key = {'ori_img':'','dst_img':'','dst_w':'','dst_h':'','save_q':75}  arg = {}  for key in args_key:    if key in args:      arg[key] = args[key]  im = image.open(arg['ori_img'])  ori_w,ori_h = im.size  widthRatio = heightRatio = None  ratio = 1  if (ori_w and ori_w > arg['dst_w']) or (ori_h and ori_h > arg['dst_h']):    if arg['dst_w'] and ori_w > arg['dst_w']:      widthRatio = float(arg['dst_w']) / ori_w #正确获取小数的方式    if arg['dst_h'] and ori_h > arg['dst_h']:      heightRatio = float(arg['dst_h']) / ori_h    if widthRatio and heightRatio:      if widthRatio < heightRatio:        ratio = widthRatio      else:        ratio = heightRatio    if widthRatio and not heightRatio:      ratio = widthRatio    if heightRatio and not widthRatio:      ratio = heightRatio    newWidth = int(ori_w * ratio)    newHeight = int(ori_h * ratio)  else:    newWidth = ori_w    newHeight = ori_h  im.resize((newWidth,newHeight),image.ANTIALIAS).save(arg['dst_img'],quality=arg['save_q'])  '''  image.ANTIALIAS还有如下值:  NEAREST: use nearest neighbour  BILINEAR: linear interpolation in a 2x2 environment  BICUBIC:cubic spline interpolation in a 4x4 environment  ANTIALIAS:best down-sizing filter  '''#裁剪压缩图片def clipResizeImg(**args):  args_key = {'ori_img':'','dst_img':'','dst_w':'','dst_h':'','save_q':75}  arg = {}  for key in args_key:    if key in args:      arg[key] = args[key]  im = image.open(arg['ori_img'])  ori_w,ori_h = im.size  dst_scale = float(arg['dst_h']) / arg['dst_w'] #目标高宽比  ori_scale = float(ori_h) / ori_w #原高宽比  if ori_scale >= dst_scale:    #过高    width = ori_w    height = int(width*dst_scale)    x = 0    y = (ori_h - height) / 3  else:    #过宽    height = ori_h    width = int(height*dst_scale)    x = (ori_w - width) / 2    y = 0  #裁剪  box = (x,y,width+x,height+y)  #这里的参数可以这么认为:从某图的(x,y)坐标开始截,截到(width+x,height+y)坐标  #所包围的图像,crop方法与php中的imagecopy方法大为不一样  newIm = im.crop(box)  im = None  #压缩  ratio = float(arg['dst_w']) / width  newWidth = int(width * ratio)  newHeight = int(height * ratio)  newIm.resize((newWidth,newHeight),image.ANTIALIAS).save(arg['dst_img'],quality=arg['save_q'])#水印(这里仅为图片水印)def waterMark(**args):  args_key = {'ori_img':'','dst_img':'','mark_img':'','water_opt':''}  arg = {}  for key in args_key:    if key in args:      arg[key] = args[key]  im = image.open(arg['ori_img'])  ori_w,ori_h = im.size  mark_im = image.open(arg['mark_img'])  mark_w,mark_h = mark_im.size  option ={'leftup':(0,0),'rightup':(ori_w-mark_w,0),'leftlow':(0,ori_h-mark_h),       'rightlow':(ori_w-mark_w,ori_h-mark_h)       }  im.paste(mark_im,option[arg['water_opt']],mark_im.convert('RGBA'))  im.save(arg['dst_img'])#Demon#源图片ori_img = 'D:/tt.jpg'#水印标mark_img = 'D:/mark.png'#水印位置(右下)water_opt = 'rightlow'#目标图片dst_img = 'D:/python_2.jpg'#目标图片大小dst_w = 94dst_h = 94#保存的图片质量save_q = 35#裁剪压缩clipResizeImg(ori_img=ori_img,dst_img=dst_img,dst_w=dst_w,dst_h=dst_h,save_q = save_q)#等比例压缩#resizeImg(ori_img=ori_img,dst_img=dst_img,dst_w=dst_w,dst_h=dst_h,save_q=save_q)#水印#waterMark(ori_img=ori_img,dst_img=dst_img,mark_img=mark_img,water_opt=water_opt)

总结

以上就是本文关于python使用pil进行图像处理(等比例压缩、裁剪)实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站:

Python内置模块turtle绘图详解

Python中pygal绘制雷达图代码分享

python自动裁剪图像代码分享

如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!


  • 上一条:
    Python最火、R极具潜力 2017机器学习调查报告
    下一条:
    让Python更加充分的使用Sqlite3
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在windows10中升级go版本至1.24后LiteIDE的Ctrl+左击无法跳转问题解决方案(0个评论)
    • 智能合约Solidity学习CryptoZombie第四课:僵尸作战系统(0个评论)
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(95个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客