侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

python自动裁剪图像代码分享

Python  /  管理员 发布于 7年前   158

本代码可以帮你自动剪切掉图片的边缘空白区域,如果你的图片有大片空白区域(只要是同一颜色形成一定的面积就认为是空白区域),下面的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好玩的项目―色情图片识别代码分享

Python生成数字图片代码分享


  • 上一条:
    python shell根据ip获取主机名代码示例
    下一条:
    分享一个简单的python读写文件脚本
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客