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使用正则表达式匹配字符串开头并打印示例
Jan 11 Python
详解python中的 is 操作符
Dec 26 Python
浅析python协程相关概念
Jan 20 Python
基于python进行桶排序与基数排序的总结
May 29 Python
Python实现曲线拟合操作示例【基于numpy,scipy,matplotlib库】
Jul 12 Python
python实现向微信用户发送每日一句 python实现微信聊天机器人
Mar 27 Python
Python树莓派学习笔记之UDP传输视频帧操作详解
Nov 15 Python
python的range和linspace使用详解
Nov 27 Python
python matplotlib画盒图、子图解决坐标轴标签重叠的问题
Jan 19 Python
opencv python Canny边缘提取实现过程解析
Feb 03 Python
python多维数组分位数的求取方式
Mar 03 Python
利用keras使用神经网络预测销量操作
Jul 07 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的邮件群发系统phplist配置方法详细总结
2016/03/30 PHP
一种JavaScript的设计模式
2006/11/22 Javascript
jQuery .attr()和.removeAttr()方法操作元素属性示例
2013/07/16 Javascript
javascript禁制后退键(Backspace)实例代码
2013/11/15 Javascript
node.js中的console.error方法使用说明
2014/12/10 Javascript
jQuery插件Zclip实现完美兼容个浏览器点击复制内容到剪贴板
2015/04/30 Javascript
JavaScript中的getTimezoneOffset()方法使用详解
2015/06/10 Javascript
javascript实现查找数组中最大值方法汇总
2016/02/13 Javascript
前端js文件合并的三种方式推荐
2016/05/19 Javascript
纯JS代码实现隔行变色鼠标移入高亮
2016/11/23 Javascript
js document.getElementsByClassName的使用介绍与自定义函数
2016/11/25 Javascript
js实现点击每个li节点,都弹出其文本值及修改
2016/12/15 Javascript
jquery.validate.js 多个相同name的处理方式
2017/07/10 jQuery
Angularjs自定义指令实现分页插件(DEMO)
2017/09/16 Javascript
JS实现简单的点赞与踩功能示例
2018/12/05 Javascript
Vue中rem与postcss-pxtorem的应用详解
2019/11/20 Javascript
[01:02:17]2014 DOTA2华西杯精英邀请赛 5 24 DK VS VG
2014/05/26 DOTA
Python制作爬虫抓取美女图
2016/01/20 Python
python thrift搭建服务端和客户端测试程序
2018/01/17 Python
通过实例解析python subprocess模块原理及用法
2020/10/10 Python
Python常用扩展插件使用教程解析
2020/11/02 Python
Python 用__new__方法实现单例的操作
2020/12/11 Python
python绕过图片滑动验证码实现爬取PTA所有题目功能 附源码
2021/01/06 Python
python3 kubernetes api的使用示例
2021/01/12 Python
Lacoste美国官网:经典POLO衫品牌
2016/10/12 全球购物
美国汽配连锁巨头Pep Boys官网:轮胎更换、汽车维修服务和汽车零部件
2017/01/14 全球购物
英国在线购买马术服装:EQUUS
2019/07/12 全球购物
Java中实现多态的机制是什么?
2014/12/07 面试题
nohup的用法
2012/11/26 面试题
品德评语大全
2014/05/05 职场文书
个人求职信范文
2014/05/24 职场文书
班级管理经验交流材料
2015/11/02 职场文书
Python机器学习三大件之一numpy
2021/05/10 Python
为什么mysql字段要使用NOT NULL
2021/05/13 MySQL
java代码实现空间切割
2022/01/18 Java/Android
Python pyecharts绘制条形图详解
2022/04/02 Python