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 04 Python
python下10个简单实例代码
Nov 15 Python
使用python实现链表操作
Jan 26 Python
Python实现PS滤镜特效Marble Filter玻璃条纹扭曲效果示例
Jan 29 Python
Python文件监听工具pyinotify与watchdog实例
Oct 15 Python
python环境路径配置以及命令行运行脚本
Apr 02 Python
用sqlalchemy构建Django连接池的实例
Aug 29 Python
Python浮点数四舍五入问题的分析与解决方法
Nov 19 Python
使用Python实现正态分布、正态分布采样
Nov 20 Python
基于Python 中函数的 收集参数 机制
Dec 21 Python
浅谈python输出列表元素的所有排列形式
Feb 26 Python
python 实现两个变量值进行交换的n种操作
Jun 02 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中的函数嵌套层数限制分析
2011/06/13 PHP
php socket客户端及服务器端应用实例
2014/07/04 PHP
在WordPress中实现发送http请求的相关函数解析
2015/12/29 PHP
阿里云的WindowsServer2016上部署php+apache
2018/07/17 PHP
Laravel 队列使用的实现
2019/01/08 PHP
PHP 出现 http500 错误的解决方法
2021/03/09 PHP
jquery.fileEveryWhere.js 一个跨浏览器的file显示插件
2011/10/24 Javascript
node.js中watch机制详解
2014/11/17 Javascript
2014 年最热门的21款JavaScript框架推荐
2014/12/25 Javascript
JS限制文本框只能输入数字和字母方法
2015/02/28 Javascript
原生js仿jquery一些常用方法(必看篇)
2016/09/20 Javascript
jQuery插件FusionCharts绘制的3D双柱状图效果示例【附demo源码】
2017/04/20 jQuery
ES6新特性:使用export和import实现模块化详解
2017/07/31 Javascript
vue bus全局事件中心简单Demo详解
2018/02/26 Javascript
vue使用高德地图根据坐标定位点的实现代码
2019/08/22 Javascript
vue中实现点击按钮滚动到页面对应位置的方法(使用c3平滑属性实现)
2019/12/29 Javascript
vuex的数据渲染与修改浅析
2020/11/26 Vue.js
Vue基本指令实例图文讲解
2021/02/25 Vue.js
[56:38]DOTA2-DPC中国联赛正赛Aster vs Magma BO3 第一场 3月5日
2021/03/11 DOTA
基于Python中capitalize()与title()的区别详解
2017/12/09 Python
python使用turtle绘制分形树
2018/06/22 Python
关于Tensorflow 模型持久化详解
2020/02/12 Python
pandas中read_csv、rolling、expanding用法详解
2020/04/21 Python
Python绘制动态水球图过程详解
2020/06/03 Python
一款纯css3实现的鼠标悬停动画按钮
2014/12/29 HTML / CSS
方太官方网上商城:销售方太抽油烟机、燃气灶、消毒柜等
2017/01/17 全球购物
入团者的自我评价分享
2013/12/02 职场文书
医院护士专业个人的求职信
2013/12/09 职场文书
家具促销活动方案
2014/02/16 职场文书
婚庆司仪主持词
2014/03/15 职场文书
保证书范文大全
2014/04/28 职场文书
通知范文怎么写
2015/04/16 职场文书
2015迎新晚会开场白
2015/05/29 职场文书
2016银行求职自荐信
2016/01/28 职场文书
anaconda python3.8安装后降级
2021/06/11 Python
一篇文章带你深入了解Mysql触发器
2021/08/02 MySQL