使用PIL修剪空白 [英] Trim whitespace using PIL

查看:182
本文介绍了使用PIL修剪空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一个简单的解决方案来修剪PIL中的图像上的空白?

Is there a simple solution to trim whitespace on the image in PIL?

ImageMagick可以通过以下方式轻松支持它:

ImageMagick has easy support for it in following way:

convert test.jpeg -fuzz 7% -trim test_trimmed.jpeg

我找到了PIL的解决方案:

I found a solution for PIL:

from PIL import Image, ImageChops

def trim(im, border):
    bg = Image.new(im.mode, im.size, border)
    diff = ImageChops.difference(im, bg)
    bbox = diff.getbbox()
    if bbox:
        return im.crop(bbox)

但是这个解决方案有缺点:

But this solution has disadvantages:


  1. 我需要定义 border 颜色对我来说这不是什么大问题,我的图片有白色背景

  2. 最不利的是,这个PIL解决方案不支持ImageMagick的 -fuzz 键。添加一些模糊裁剪。因为我可以有一些jpeg压缩工件和不需要的巨大阴影。

  1. I need to define border color, it is not a big deal for me, my images has white background
  2. And the most disadvantage, This PIL solution doesn't support ImageMagick's -fuzz key. To add some fuzzy cropping. as I can have some jpeg compression artifacts and unneeded huge shadows.

可能PIL有一些内置函数吗?
或者有一些快速的解决方案?

May be PIL has some built in functions for it? Or there is some fast solution?

推荐答案

我认为PIL内置的任何东西都不能做这个。但我已经修改了你的代码,所以它会这样做。

I don't think there is anything built in to PIL that can do this. But I've modified your code so it will do it.


  • 它使用 getpixel 从左上角的像素获取边框颜色,所以你不需要传递颜色。

  • 从差异图像中减去一个标量,这是在 100,100,100下使所有值饱和的快速方法(在我的例子中)为零。因此,删除压缩产生的任何摆动都是一种巧妙的方法。

  • It gets the border colour from the top left pixel, using getpixel, so you don't need to pass the colour.
  • Subtracts a scalar from the differenced image, this is a quick way of saturating all values under 100, 100, 100 (in my example) to zero. So is a neat way to remove any 'wobble' resulting from compression.

代码:

from PIL import Image, ImageChops

def trim(im):
    bg = Image.new(im.mode, im.size, im.getpixel((0,0)))
    diff = ImageChops.difference(im, bg)
    diff = ImageChops.add(diff, diff, 2.0, -100)
    bbox = diff.getbbox()
    if bbox:
        return im.crop(bbox)

im = Image.open("bord3.jpg")
im = trim(im)
im.show()

重度压缩的jpeg:

裁剪:

吵闹的jpeg:

裁剪:

这篇关于使用PIL修剪空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆