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中用于计算对数的log()方法
May 15 Python
windows下安装Python和pip终极图文教程
Mar 05 Python
python 类对象和实例对象动态添加方法(分享)
Dec 31 Python
python 对类的成员函数开启线程的方法
Jan 22 Python
Python字典的核心底层原理讲解
Jan 24 Python
python tkinter canvas 显示图片的示例
Jun 13 Python
解决.ui文件生成的.py文件运行不出现界面的方法
Jun 19 Python
Python之数据序列化(json、pickle、shelve)详解
Aug 30 Python
wxPython色环电阻计算器
Nov 18 Python
Python3 Tkinkter + SQLite实现登录和注册界面
Nov 19 Python
python编写softmax函数、交叉熵函数实例
Jun 11 Python
用python开发一款操作MySQL的小工具
May 12 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设计模式 Mediator (中介者模式)
2011/06/26 PHP
php入门学习知识点八 PHP中for循环基本应用之九九乘法口绝表
2011/07/14 PHP
PHP函数microtime()用法与说明
2013/12/04 PHP
mysql_escape_string()函数用法分析
2016/04/25 PHP
Yii2中OAuth扩展及QQ互联登录实现方法
2016/05/16 PHP
php微信开发之音乐回复功能
2018/06/14 PHP
MooBox 基于Mootools的对话框插件
2012/01/20 Javascript
Jquery实现视频播放页面的关灯开灯效果
2013/05/27 Javascript
在js文件中如何获取basePath处理js路径问题
2013/07/10 Javascript
整理的比较全的event对像在ie与firefox浏览器中的区别
2013/11/25 Javascript
javascript移动设备Web开发中对touch事件的封装实例
2014/06/05 Javascript
基于jQuery实现动态数字展示效果
2015/08/12 Javascript
利用select实现年月日三级联动的日期选择效果【推荐】
2016/12/13 Javascript
js实现前端图片上传即时预览功能
2017/08/02 Javascript
详解vue-cli脚手架中webpack配置方法
2018/08/22 Javascript
webpack4 处理SCSS的方法示例
2018/09/03 Javascript
js回溯法计算最佳旅行线路代码实例
2019/09/11 Javascript
基于postman获取动态数据过程详解
2020/09/08 Javascript
[55:32]2018DOTA2亚洲邀请赛 4.4 淘汰赛 EG vs LGD 第二场
2018/04/05 DOTA
列举Python中吸引人的一些特性
2015/04/09 Python
python实现读取并显示图片的两种方法
2017/01/13 Python
PyTorch实现AlexNet示例
2020/01/14 Python
python的sys.path模块路径添加方式
2020/03/09 Python
html5指南-3.如何实现html元素拖拽功能
2013/01/07 HTML / CSS
仿酷狗html5手机音乐播放器主要部分代码
2013/05/15 HTML / CSS
解决HTML5中的audio在手机端和微信端的不能自动播放问题
2019/11/04 HTML / CSS
TripAdvisor斯洛伐克:阅读评论、比较价格和酒店预订
2018/04/25 全球购物
实习生的自我评价
2014/01/08 职场文书
合作意向书格式及范文
2014/03/31 职场文书
化妆品活动策划方案
2014/05/23 职场文书
给老师的一封感谢信
2015/01/20 职场文书
工作失职自我检讨书
2015/05/05 职场文书
2015社区个人工作总结范文
2015/05/13 职场文书
跳高加油稿
2015/07/21 职场文书
初中同学会致辞
2015/08/01 职场文书
MySQL安装后默认自带数据库的作用详解
2021/04/27 MySQL