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简单猜数游戏实例
Jul 09 Python
Python探索之SocketServer详解
Oct 28 Python
python2.6.6如何升级到python2.7.14
Apr 08 Python
Django migrations 默认目录修改的方法教程
Sep 28 Python
Python3实现的简单三级菜单功能示例
Mar 12 Python
Python操作SQLite/MySQL/LMDB数据库的方法
Nov 07 Python
python 解决print数组/矩阵无法完整输出的问题
Feb 19 Python
python GUI库图形界面开发之PyQt5工具栏控件QToolBar的详细使用方法与实例
Feb 28 Python
浅谈keras 的抽象后端(from keras import backend as K)
Jun 16 Python
深入分析python 排序
Aug 24 Python
python+appium+yaml移动端自动化测试框架实现详解
Nov 24 Python
Django 权限管理(permissions)与用户组(group)详解
Nov 30 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
DOM精简教程
2006/10/03 Javascript
线路分流自动跳转代码;希望对大家有用!
2006/12/02 Javascript
javascript replace方法与正则表达式
2008/02/19 Javascript
IE关闭时判断及AJAX注销案例学习
2013/02/18 Javascript
A标签触发onclick事件而不跳转的多种解决方法
2013/06/27 Javascript
js实现网页倒计时、网站已运行时间功能的代码3例
2014/04/14 Javascript
使用JQ来编写最基本的淡入淡出效果附演示动画
2014/10/31 Javascript
基于jquery实现简单的分页控件
2016/03/17 Javascript
javascript中this指向详解
2016/04/23 Javascript
如何用JS判断两个数字的大小
2016/07/21 Javascript
详解如何较好的使用js
2016/12/16 Javascript
解决微信内置浏览器返回上一页强制刷新问题方法
2017/02/05 Javascript
Angular 4 依赖注入学习教程之FactoryProvider的使用(四)
2017/06/04 Javascript
Javascript中的作用域及块级作用域
2017/12/08 Javascript
node 解析图片二维码的内容代码实例
2019/09/11 Javascript
基于Nuxt.js项目的服务端性能优化与错误检测(容错处理)
2019/10/23 Javascript
[01:05:29]DOTA2-DPC中国联赛 正赛 PSG.LGD vs Aster BO3 第二场 1月24日
2021/03/11 DOTA
Python实现屏幕截图的代码及函数详解
2016/10/01 Python
flask session组件的使用示例
2018/12/25 Python
Django打印出在数据库中执行的语句问题
2019/07/25 Python
python json.dumps中文乱码问题解决
2020/04/01 Python
python日志通过不同的等级打印不同的颜色(示例代码)
2021/01/13 Python
美国在线乐器和设备商店:Musician’s Friend
2018/07/06 全球购物
法国面料和小百货在线商店:Mondial Tissus
2019/03/23 全球购物
Perfume’s Club美国官网:西班牙第一家在线美容店
2020/06/10 全球购物
高三体育教学反思
2014/01/29 职场文书
学校宣传标语
2014/06/18 职场文书
《中国梦我的梦》大学生演讲稿
2014/08/20 职场文书
工作作风建设心得体会
2014/10/22 职场文书
经典搞笑版检讨书
2015/02/19 职场文书
千手观音观后感
2015/06/03 职场文书
陪护人员误工证明
2015/06/24 职场文书
2016元旦文艺汇演主持词
2015/07/06 职场文书
中秋晚会致辞
2015/07/31 职场文书
小学四年级班务总结该怎么写?
2019/08/16 职场文书
MYSQL(电话号码,身份证)数据脱敏的实现
2021/05/28 MySQL