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实现无证书加密解密实例
Oct 27 Python
Python应用03 使用PyQT制作视频播放器实例
Dec 07 Python
python模块之re正则表达式详解
Feb 03 Python
Python实现两款计算器功能示例
Dec 19 Python
Python面向对象程序设计之继承与多继承用法分析
Jul 13 Python
tensorflow 恢复指定层与不同层指定不同学习率的方法
Jul 26 Python
Django添加favicon.ico图标的示例代码
Aug 07 Python
解决Python对齐文本字符串问题
Aug 28 Python
基于Python实现剪切板实时监控方法解析
Sep 11 Python
python安装后的目录在哪里
Jun 21 Python
Python3爬虫ChromeDriver的安装实例
Feb 06 Python
Pytorch之扩充tensor的操作
Mar 04 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 反向排序和随机排序代码
2010/06/30 PHP
配置eAccelerator和XCache扩展来加速PHP程序的执行
2015/12/22 PHP
Yii2增加验证码步骤详解
2016/04/25 PHP
php获取开始与结束日期之间所有日期的方法
2016/11/29 PHP
thinkPHP框架动态配置用法实例分析
2018/06/14 PHP
thinkPHP5使用Rabc实现权限管理
2019/08/28 PHP
[全兼容哦]--实用、简洁、炫酷的页面转入效果loing
2007/05/07 Javascript
JavaScript confirm选择判断
2008/10/18 Javascript
extjs实现选择多表自定义查询功能 前台部分(ext源码)
2011/12/20 Javascript
基于dom编程中 动态创建与删除元素的使用
2013/04/17 Javascript
『jQuery』取指定url格式及分割函数应用
2013/04/22 Javascript
根据身份证号自动输出相关信息(籍贯,出身日期,性别)
2013/11/15 Javascript
Document.location.href和.replace的区别示例介绍
2014/03/04 Javascript
jquery form 加载数据示例
2014/04/21 Javascript
Nodejs进程管理模块forever详解
2014/06/01 NodeJs
Google官方支持的NodeJS访问API,提供后台登录授权
2014/07/29 NodeJs
JavaScript实现数字数组按照倒序排列的方法
2015/04/06 Javascript
jQuery下拉美化搜索表单效果代码分享
2015/08/25 Javascript
深入理解Webpack 中路径的配置
2017/06/17 Javascript
详解nodejs中express搭建权限管理系统
2017/09/15 NodeJs
官方推荐react-navigation的具体使用详解
2018/05/08 Javascript
[02:44]2014DOTA2 国际邀请赛中国区预选赛 大神红毯秀
2014/05/25 DOTA
[02:59]DOTA2完美大师赛主赛事第三日精彩集锦
2017/11/25 DOTA
Python 类与元类的深度挖掘 I【经验】
2016/05/06 Python
django开发教程之利用缓存文件进行页面缓存的方法
2017/11/10 Python
Numpy掩码式数组详解
2018/04/17 Python
下载python中Crypto库报错:ModuleNotFoundError: No module named ‘Crypto’的解决
2018/04/23 Python
详解10个可以快速用Python进行数据分析的小技巧
2019/06/24 Python
Python读取JSON数据操作实例解析
2020/05/18 Python
Html5写一个简单的俄罗斯方块小游戏
2019/12/03 HTML / CSS
高中自我鉴定范文
2013/11/03 职场文书
观看焦裕禄观后感
2015/06/09 职场文书
MySQL pt-slave-restart工具的使用简介
2021/04/07 MySQL
Java获取e.printStackTrace()打印的信息方式
2021/08/07 Java/Android
Java数据结构之堆(优先队列)
2022/05/20 Java/Android
彻底弄懂Python中的回调函数(callback)
2022/06/25 Python