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实现Linux下守护进程的编写方法
Aug 22 Python
python kmeans聚类简单介绍和实现代码
Feb 23 Python
python pandas.DataFrame选取、修改数据最好用.loc,.iloc,.ix实现
Jun 11 Python
python用pandas数据加载、存储与文件格式的实例
Dec 07 Python
Django Admin中增加导出CSV功能过程解析
Sep 04 Python
详解Python3 pickle模块用法
Sep 16 Python
django2.2安装错误最全的解决方案(小结)
Sep 24 Python
Python MongoDB 插入数据时已存在则不执行,不存在则插入的解决方法
Sep 24 Python
python实现飞船大战
Apr 24 Python
Keras 数据增强ImageDataGenerator多输入多输出实例
Jul 03 Python
Python实现AES加密,解密的两种方法
Oct 03 Python
python实现PolynomialFeatures多项式的方法
Jan 06 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 将bmp图片转为jpg等其他任意格式的图片
2009/06/29 PHP
PHP 模拟$_PUT实现代码
2010/03/15 PHP
《PHP编程最快明白》第七讲:php图片验证码与缩略图
2010/11/01 PHP
PHP生成二维码的两个方法和实例
2014/07/01 PHP
php文件上传后端处理小技巧
2016/05/22 PHP
PHP基于GD库实现的生成图片缩略图函数示例
2017/07/05 PHP
jquery $.ajax入门应用一
2008/11/19 Javascript
关于js datetime的那点事
2011/11/15 Javascript
javascript数组去重3种方法的性能测试与比较
2013/03/26 Javascript
JS日期和时间选择控件升级版(自写)
2013/08/02 Javascript
ExtJS4如何给同一个formpanel不同的url
2014/05/02 Javascript
JavaScript对象之深度克隆介绍
2014/12/08 Javascript
jQuery+PHP+MySQL实现无限级联下拉框效果
2016/02/19 Javascript
jquery使用Cookie和JSON记录用户最近浏览历史
2016/04/19 Javascript
vue 实现数字滚动增加效果的实例代码
2018/07/06 Javascript
了解JavaScript函数中的默认参数
2019/05/30 Javascript
layui实现三级联动效果
2019/07/26 Javascript
Vue 技巧之控制父类的 slot
2020/02/24 Javascript
vue-cli4.x创建企业级项目的方法步骤
2020/06/18 Javascript
pycharm 使用心得(八)如何调用另一文件中的函数
2014/06/06 Python
Python使用shelve模块实现简单数据存储的方法
2015/05/20 Python
Python的Django框架安装全攻略
2015/07/15 Python
通过mod_python配置运行在Apache上的Django框架
2015/07/22 Python
Python网络爬虫项目:内容提取器的定义
2016/10/25 Python
Pycharm之快速定位到某行快捷键的方法
2019/01/20 Python
python2爬取百度贴吧指定关键字和图片代码实例
2019/08/14 Python
python定位xpath 节点位置的方法
2019/08/27 Python
python实现俄罗斯方块小游戏
2020/04/24 Python
Sneaker Studio法国:购买运动鞋
2018/06/08 全球购物
农村产权制度改革实施方案
2014/03/21 职场文书
网吧最新创业计划书范文
2014/03/27 职场文书
员工安全承诺书
2014/05/22 职场文书
煤矿安全生产标语
2014/06/06 职场文书
婚庆开业庆典主持词
2015/06/30 职场文书
安全温馨提示语大全
2015/07/14 职场文书
python实现网络五子棋
2021/04/11 Python