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 24 Python
Python爬取十篇新闻统计TF-IDF
Jan 03 Python
python3.5 tkinter实现页面跳转
Jan 30 Python
pytorch permute维度转换方法
Dec 14 Python
树莓派与PC端在局域网内运用python实现即时通讯
Jun 22 Python
python3实现二叉树的遍历与递归算法解析(小结)
Jul 03 Python
解决Django中修改js css文件但浏览器无法及时与之改变的问题
Aug 31 Python
python使用matplotlib绘制雷达图
Oct 18 Python
python自动点赞功能的实现思路
Feb 26 Python
Tensorflow中的dropout的使用方法
Mar 13 Python
详解用Pytest+Allure生成漂亮的HTML图形化测试报告
Mar 31 Python
python程序需要编译吗
Jun 19 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应用程序来获取Web服务器的状态信息
2006/10/09 PHP
PHP的魔术常量__METHOD__简介
2014/07/08 PHP
PHP页面转UTF-8中文编码乱码的解决办法
2015/10/20 PHP
非常实用的php验证码类
2016/05/15 PHP
php实现简单加入购物车功能
2017/03/07 PHP
jQuery 1.2.x 升? 1.3.x 注意事项
2009/05/06 Javascript
javascript中拼接HTML字符串的最快、最好的方法
2014/06/07 Javascript
常用的JavaScript模板引擎介绍
2015/02/28 Javascript
JavaScript实现在页面间传值的方法
2015/04/07 Javascript
jquery控制页面部分刷新的方法
2015/06/24 Javascript
深入学习JavaScript中的Rest参数和参数默认值
2015/07/28 Javascript
jquery自动补齐功能插件flexselect用法示例
2016/08/06 Javascript
基于Bootstrap的Metronic框架实现页面链接收藏夹功能
2016/08/29 Javascript
js时间控件只显示年月
2017/01/08 Javascript
原生js实现简单的链式操作
2017/07/04 Javascript
JavaScript变量类型以及变量作用域详解
2017/08/14 Javascript
Vuex入门到上手教程
2018/06/20 Javascript
ES6入门教程之let、const的使用方法
2019/04/13 Javascript
js简单遍历获取对象中的属性值的方法示例
2019/06/19 Javascript
[01:16:37]【全国守擂赛】第三周决赛 Dark Knight vs. 一个弱队
2020/05/04 DOTA
在Python中关于中文编码问题的处理建议
2015/04/08 Python
TensorFlow如何实现反向传播
2018/02/06 Python
Django学习教程之静态文件的调用详解
2018/05/08 Python
Python中的集合介绍
2019/01/28 Python
Django打印出在数据库中执行的语句问题
2019/07/25 Python
容易被忽略的Python内置类型
2020/09/03 Python
python“静态”变量、实例变量与本地变量的声明示例
2020/11/13 Python
优秀教师获奖感言
2014/01/31 职场文书
创建精神文明单位实施方案
2014/03/08 职场文书
2015国际残疾人日活动总结
2015/03/24 职场文书
新学期开学标语2015
2015/07/16 职场文书
2019大学生实习报告
2019/06/21 职场文书
my.ini优化mysql数据库性能的十个参数(推荐)
2021/05/26 MySQL
pytorch分类模型绘制混淆矩阵以及可视化详解
2022/04/07 Python
Python  lambda匿名函数和三元运算符
2022/04/19 Python
Redis 报错 error:NOAUTH Authentication required
2022/05/15 Redis