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 相关文章推荐
详解Python3中yield生成器的用法
Aug 20 Python
python 中的list和array的不同之处及转换问题
Mar 13 Python
Python requests模块实例用法
Feb 11 Python
python flask框架实现传数据到js的方法分析
Jun 11 Python
Python爬取视频(其实是一篇福利)过程解析
Aug 01 Python
如何在mac环境中用python处理protobuf
Dec 25 Python
为什么黑客都用python(123个黑客必备的Python工具)
Jan 31 Python
Python小整数对象池和字符串intern实例解析
Mar 21 Python
Python decimal模块使用方法详解
Jun 08 Python
Python Tkinter实例——模拟掷骰子
Oct 24 Python
python中pyqtgraph知识点总结
Jan 26 Python
Python集合set()使用的方法详解
Mar 18 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
下载文件的点击数回填
2006/10/09 PHP
php intval的测试代码发现问题
2008/07/27 PHP
php命令行使用方法和命令行参数说明
2014/04/08 PHP
php获取textarea的值并处理回车换行的方法
2014/10/20 PHP
Yii2框架实现登陆添加验证码功能示例
2018/07/12 PHP
jQuery解析XML与传统JavaScript方法的差别实例分析
2015/03/05 Javascript
DEDECMS如何为文章添加HOT NEW标志图片
2015/08/14 Javascript
jQuery实现分章节锚点“回到顶部”动画特效代码
2015/10/23 Javascript
jQuery使用$.ajax进行异步刷新的方法(附demo下载)
2015/12/04 Javascript
聊一聊JS中的prototype
2016/09/29 Javascript
vue的props实现子组件随父组件一起变化
2016/10/27 Javascript
JS实现字符串转驼峰格式的方法
2016/12/16 Javascript
基于vue2.0实现简单轮播图
2017/11/27 Javascript
微信小程序表单验证功能完整实例
2017/12/01 Javascript
详解JavaScript基础知识(JSON、Function对象、原型、引用类型)
2018/01/16 Javascript
[56:17]NB vs Infamous 2019国际邀请赛淘汰赛 败者组 BO3 第三场 8.22
2019/09/05 DOTA
Python 网络编程起步(Socket发送消息)
2008/09/06 Python
基于进程内通讯的python聊天室实现方法
2015/06/28 Python
django实现前后台交互实例
2017/08/07 Python
python读取目录下最新的文件夹方法
2018/12/24 Python
Python函数参数匹配模型通用规则keyword-only参数详解
2019/06/10 Python
python实现单链表的方法示例
2019/09/03 Python
使用Keras 实现查看model weights .h5 文件的内容
2020/06/09 Python
Pytorch框架实现mnist手写库识别(与tensorflow对比)
2020/07/20 Python
mac安装python3后使用pip和pip3的区别说明
2020/09/01 Python
100%有机精油,美容油:House of Pure Essence
2018/10/30 全球购物
有模特经验的简历自我评价
2013/09/19 职场文书
新闻专业个人自我评价
2013/09/21 职场文书
金属材料工程毕业生个人的自我评价
2013/11/28 职场文书
医生党的群众路线教育实践活动个人对照检查材料
2014/09/23 职场文书
大学生暑期社会实践证明范本
2014/10/24 职场文书
逃课检讨书范文
2015/05/06 职场文书
指导教师推荐意见
2015/06/05 职场文书
八年级作文之感悟亲情
2019/11/20 职场文书
Vue-Element-Admin集成自己的接口实现登录跳转
2021/06/23 Vue.js
集英社今正式宣布 成立游戏公司“集英社Games”
2022/03/31 其他游戏