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实现类似jQuery使用中的链式调用的示例
Jun 16 Python
Python 模块EasyGui详细介绍
Feb 19 Python
关于python的list相关知识(推荐)
Aug 30 Python
Python使用zip合并相邻列表项的方法示例
Mar 17 Python
Python对切片命名的实现方法
Oct 16 Python
python 实现兔子生兔子示例
Nov 21 Python
python之array赋值技巧分享
Nov 28 Python
Python PyQt5整理介绍
Apr 01 Python
python 画图 图例自由定义方式
Apr 17 Python
Python爬虫如何应对Cloudflare邮箱加密
Jun 24 Python
如何用 Python 子进程关闭 Excel 自动化中的弹窗
May 07 Python
Python 如何将integer转化为罗马数(3999以内)
Jun 05 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
PHP数组相关函数汇总
2015/03/24 PHP
对php 判断http还是https,以及获得当前url的方法详解
2019/01/15 PHP
javascript中检测变量的类型的代码
2010/12/28 Javascript
js检测网络是否具体连接功能的代码
2014/05/23 Javascript
js中字符串编码函数escape()、encodeURI()、encodeURIComponent()区别详解
2016/04/01 Javascript
jQuery设置单选按钮radio选中/不可用的实例代码
2016/06/24 Javascript
Javascript设计模式之装饰者模式详解篇
2017/01/17 Javascript
Bootstrap导航条学习使用(一)
2017/02/08 Javascript
Underscore之Array_动力节点Java学院整理
2017/07/10 Javascript
JavaScript函数中的this四种绑定形式
2017/08/15 Javascript
自制简易打赏功能的实例
2017/09/02 Javascript
浅谈node的事件机制
2017/10/09 Javascript
vue实现标签云效果的方法详解
2019/08/28 Javascript
在vue中使用echarts(折线图的demo,markline用法)
2020/07/20 Javascript
python使用in操作符时元组和数组的区别分析
2015/05/19 Python
python处理大数字的方法
2015/05/27 Python
itchat和matplotlib的结合使用爬取微信信息的实例
2017/08/25 Python
shell命令行,一键创建 python 模板文件脚本方法
2018/03/20 Python
pytorch构建网络模型的4种方法
2018/04/13 Python
numpy实现合并多维矩阵、list的扩展方法
2018/05/08 Python
python selenium自动上传有赞单号的操作方法
2018/07/05 Python
python/sympy求解矩阵方程的方法
2018/11/08 Python
python实发邮件实例详解
2019/11/11 Python
django admin 添加自定义链接方式
2020/03/11 Python
keras打印loss对权重的导数方式
2020/06/10 Python
5个你不知道的HTML5的接口介绍
2013/08/07 HTML / CSS
美国知名的百货清仓店:Neiman Marcus Last Call
2016/08/03 全球购物
印度尼西亚最大和最全面的网络商城:Blibli.com
2017/10/04 全球购物
应用化学专业职业生涯规划书
2013/12/31 职场文书
法务专员岗位职责
2014/01/02 职场文书
2014年公路养护工作总结
2014/12/04 职场文书
鲁迅故居导游词
2015/02/05 职场文书
活着观后感
2015/06/03 职场文书
2019银行员工个人工作自我鉴定
2019/06/27 职场文书
Pytorch实现图像识别之数字识别(附详细注释)
2021/05/11 Python
python异常中else的实例用法
2021/06/15 Python