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 相关文章推荐
rhythmbox中文名乱码问题解决方法
Sep 06 Python
python中黄金分割法实现方法
May 06 Python
Python中对象的引用与复制代码示例
Dec 04 Python
python 将数据保存为excel的xls格式(实例讲解)
May 03 Python
python 实现语音聊天机器人的示例代码
Dec 02 Python
python实现几种归一化方法(Normalization Method)
Jul 31 Python
python-opencv获取二值图像轮廓及中心点坐标的代码
Aug 27 Python
详解Django admin高级用法
Nov 06 Python
Python脚本操作Excel实现批量替换功能
Nov 20 Python
Python动态导入模块:__import__、importlib、动态导入的使用场景实例分析
Mar 30 Python
Python实现删除某列中含有空值的行的示例代码
Jul 20 Python
用Python将GIF动图分解成多张静态图片
Jun 11 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.ini 中文版
2006/10/28 PHP
PHP 木马攻击防御技巧
2009/06/13 PHP
PHP 数组遍历foreach语法结构及实例
2016/06/13 PHP
兼容多浏览器的字幕特效Marquee的通用js类
2008/07/20 Javascript
给jqGrid数据行添加修改和删除操作链接(之一)
2011/11/04 Javascript
关于JAVASCRIPT urldecode URL解码的问题
2012/01/08 Javascript
javascript学习笔记(十四) window对象使用介绍
2012/06/20 Javascript
jquery+javascript编写国籍控件
2015/02/12 Javascript
详解iframe与frame的区别
2016/01/13 Javascript
jQuery四种选择器使用及示例
2016/06/05 Javascript
微信小程序 实例应用(记账)详解
2016/09/28 Javascript
微信小程序 textarea 组件详解及简单实例
2017/01/10 Javascript
利用Angular+Angular-Ui实现分页(代码加简单)
2017/03/10 Javascript
微信小程序开发之选项卡(窗口底部TabBar)页面切换
2017/04/12 Javascript
vue中使用vue-cli接入融云实现即时通信
2019/04/19 Javascript
多个Vue项目部署到服务器的步骤记录
2020/10/22 Javascript
vue项目配置同一局域网可使用ip访问的操作
2020/10/23 Javascript
windows下安装python paramiko模块的代码
2013/02/10 Python
在Pycharm中自动添加时间日期作者等信息的方法
2019/01/16 Python
Opencv-Python图像透视变换cv2.warpPerspective的示例
2019/04/11 Python
Python 一键制作微信好友图片墙的方法
2019/05/16 Python
python django下载大的csv文件实现方法分析
2019/07/19 Python
python中enumerate() 与zip()函数的使用比较实例分析
2019/09/03 Python
python实现ip地址的包含关系判断
2020/02/07 Python
Python爬虫爬取杭州24时温度并展示操作示例
2020/03/27 Python
Django权限设置及验证方式
2020/05/13 Python
德国运动鞋网上商店:Afew Store
2018/01/05 全球购物
乌克兰在线药房:Аптека24
2019/10/30 全球购物
一些Solaris面试题
2015/12/22 面试题
2014预备党员党课学习心得范文
2014/07/08 职场文书
区长工作作风个人整改措施
2014/10/01 职场文书
医院见习报告范文
2014/11/03 职场文书
运动会主持词大全
2015/07/02 职场文书
企业安全生产规章制度
2015/08/06 职场文书
先进教师个人主要事迹材料
2015/11/03 职场文书
表扬稿表扬信的格式及范文
2019/06/24 职场文书