python自动裁剪图像代码分享


Posted in Python onNovember 25, 2017

本代码可以帮你自动剪切掉图片的边缘空白区域,如果你的图片有大片空白区域(只要是同一颜色形成一定的面积就认为是空白区域),下面的python代码可以帮你自动切除,如果是透明图像,会自动剪切大片的透明部分。

本代码需要PIL模块

pil相关介绍

PIL:Python Imaging Library,已经是Python平台事实上的图像处理标准库了。PIL功能非常强大,但API却非常简单易用。

由于PIL仅支持到Python 2.7,加上年久失修,于是一群志愿者在PIL的基础上创建了兼容的版本,名字叫Pillow,支持最新Python 3.x,又加入了许多新特性,因此,我们可以直接安装使用Pillow。

import Image, ImageChops
 
def autoCrop(image,backgroundColor=None):
  '''Intelligent automatic image cropping.
    This functions removes the usless "white" space around an image.
    
    If the image has an alpha (tranparency) channel, it will be used
    to choose what to crop.
    
    Otherwise, this function will try to find the most popular color
    on the edges of the image and consider this color "whitespace".
    (You can override this color with the backgroundColor parameter) 
 
    Input:
      image (a PIL Image object): The image to crop.
      backgroundColor (3 integers tuple): eg. (0,0,255)
         The color to consider "background to crop".
         If the image is transparent, this parameters will be ignored.
         If the image is not transparent and this parameter is not
         provided, it will be automatically calculated.
 
    Output:
      a PIL Image object : The cropped image.
  '''
   
  def mostPopularEdgeColor(image):
    ''' Compute who's the most popular color on the edges of an image.
      (left,right,top,bottom)
       
      Input:
        image: a PIL Image object
       
      Ouput:
        The most popular color (A tuple of integers (R,G,B))
    '''
    im = image
    if im.mode != 'RGB':
      im = image.convert("RGB")
     
    # Get pixels from the edges of the image:
    width,height = im.size
    left  = im.crop((0,1,1,height-1))
    right = im.crop((width-1,1,width,height-1))
    top  = im.crop((0,0,width,1))
    bottom = im.crop((0,height-1,width,height))
    pixels = left.tostring() + right.tostring() + top.tostring() + bottom.tostring()
 
    # Compute who's the most popular RGB triplet
    counts = {}
    for i in range(0,len(pixels),3):
      RGB = pixels[i]+pixels[i+1]+pixels[i+2]
      if RGB in counts:
        counts[RGB] += 1
      else:
        counts[RGB] = 1  
     
    # Get the colour which is the most popular:    
    mostPopularColor = sorted([(count,rgba) for (rgba,count) in counts.items()],reverse=True)[0][1]
    return ord(mostPopularColor[0]),ord(mostPopularColor[1]),ord(mostPopularColor[2])
   
  bbox = None
   
  # If the image has an alpha (tranparency) layer, we use it to crop the image.
  # Otherwise, we look at the pixels around the image (top, left, bottom and right)
  # and use the most used color as the color to crop.
   
  # --- For transparent images -----------------------------------------------
  if 'A' in image.getbands(): # If the image has a transparency layer, use it.
    # This works for all modes which have transparency layer
    bbox = image.split()[list(image.getbands()).index('A')].getbbox()
  # --- For non-transparent images -------------------------------------------
  elif image.mode=='RGB':
    if not backgroundColor:
      backgroundColor = mostPopularEdgeColor(image)
    # Crop a non-transparent image.
    # .getbbox() always crops the black color.
    # So we need to substract the "background" color from our image.
    bg = Image.new("RGB", image.size, backgroundColor)
    diff = ImageChops.difference(image, bg) # Substract background color from image
    bbox = diff.getbbox() # Try to find the real bounding box of the image.
  else:
    raise NotImplementedError, "Sorry, this function is not implemented yet for images in mode '%s'." % image.mode
     
  if bbox:
    image = image.crop(bbox)
     
  return image
 
 
 
#范例:裁剪透明图片:
im = Image.open('myTransparentImage.png')
cropped = autoCrop(im)
cropped.show()
 
#范例:裁剪非透明图片
im = Image.open('myImage.png')
cropped = autoCrop(im)
cropped.show()

 总结

以上就是本文关于python自动裁剪图像代码分享的全部内容,希望对大家有所帮助。如有不足之处,欢迎留言指出。感兴趣的朋友可以继续参阅本站:

Python 相关文章推荐
python字典多条件排序方法实例
Jun 30 Python
Python实现windows下模拟按键和鼠标点击的方法
Mar 13 Python
Python语言实现获取主机名根据端口杀死进程
Mar 31 Python
python中装饰器级连的使用方法示例
Sep 29 Python
python SMTP实现发送带附件电子邮件
May 22 Python
django 在原有表格添加或删除字段的实例
May 27 Python
Sanic框架基于类的视图用法示例
Jul 18 Python
Python实现将数据写入netCDF4中的方法示例
Aug 30 Python
在Python中字典根据多项规则排序的方法
Jan 21 Python
使用GitHub和Python实现持续部署的方法
May 09 Python
Django ValuesQuerySet转json方式
Mar 16 Python
Django 项目布局方法(值得推荐)
Mar 22 Python
分享一个简单的python读写文件脚本
Nov 25 #Python
python之virtualenv的简单使用方法(必看篇)
Nov 25 #Python
python多进程实现进程间通信实例
Nov 24 #Python
Python实现列表删除重复元素的三种常用方法分析
Nov 24 #Python
Python二叉树的定义及常用遍历算法分析
Nov 24 #Python
详解python上传文件和字符到PHP服务器
Nov 24 #Python
Python实现矩阵转置的方法分析
Nov 24 #Python
You might like
基于mysql的论坛(7)
2006/10/09 PHP
php中的PHP_EOL换行符详细解析
2013/10/26 PHP
PHP获得数组交集与差集的方法
2015/06/10 PHP
Maps Javascript
2007/01/22 Javascript
基于jquery实现的鼠标滑过按钮改变背景图片
2011/07/15 Javascript
Node.js安装教程和NPM包管理器使用详解
2014/08/16 Javascript
在JavaScript的AngularJS库中进行单元测试的方法
2015/06/23 Javascript
JS阻止事件冒泡行为和闭包的方法
2016/06/16 Javascript
JS 获取HTML标签内的子节点的方法
2016/09/21 Javascript
Web前端开发之水印、图片验证码
2016/11/27 Javascript
JavaScript fetch接口案例解析
2018/08/30 Javascript
angularJs提交文本框数据到后台的方法
2018/10/08 Javascript
详解使用React.memo()来优化函数组件的性能
2019/03/19 Javascript
Laravel admin实现消息提醒、播放音频功能
2019/07/10 Javascript
JavaScript实现串行请求的示例代码
2020/09/14 Javascript
Python中特殊函数集锦
2015/07/27 Python
python 不以科学计数法输出的方法
2018/07/16 Python
Django 接收Post请求数据,并保存到数据库的实现方法
2019/07/12 Python
Django自定义用户表+自定义admin后台中的字段实例
2019/11/18 Python
通过celery异步处理一个查询任务的完整代码
2019/11/19 Python
Python requests获取网页常用方法解析
2020/02/20 Python
Python 如何对文件目录操作
2020/07/10 Python
matplotlib subplot绘制多个子图的方法示例
2020/07/28 Python
python爬取股票最新数据并用excel绘制树状图的示例
2021/03/01 Python
利用CSS3的特性改变文本选中时的颜色
2013/09/11 HTML / CSS
使用HTML5原生对话框元素并轻松创建模态框组件
2019/03/06 HTML / CSS
Nordgreen英国官网:斯堪的纳维亚设计师手表
2018/10/24 全球购物
通信工程专业个人找工作求职信范文
2013/09/21 职场文书
2014年大学班长工作总结
2014/11/14 职场文书
财务出纳岗位职责
2015/03/31 职场文书
聘任通知书
2015/09/21 职场文书
一道JS算法面试题——冒泡、选择排序
2021/04/21 Javascript
python使用pywinauto驱动微信客户端实现公众号爬虫
2021/05/19 Python
详解Vue的列表渲染
2021/11/20 Vue.js
vue @click.native 绑定原生点击事件
2022/04/22 Vue.js
Windows Server 2019 域控制器安装图文教程
2022/04/28 Servers