从图像中删除所有空白空间

3
我需要从图片中删除所有空格,但我不知道该如何做。 我正在使用修剪功能来修剪边框中的空格,但是图片中间仍然存在空格。我附上了原始图像,希望能够去除其中的空格。

原始图像

我的代码:

from PIL import Image, ImageChops
import numpy


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)
    box = diff.getbbox()
    if box:
        im.crop(box).save("trim_pil.png")


im = Image.open("/home/einfochips/Documents/imagecomparsion/kroger_image_comparison/SnapshotImages/screenshot_Hide.png")
im = trim(im)

但是这段代码只能移除边框的空格,我需要同时从中间移除空格。如果可能的话,请帮忙解决,如果能够将所有五张图片保存为不同的PNG文件,那就更好了。


1
所以您想要移除图像之间的黑色区域? - N0b1ts
获取一个想法- https://stackoverflow.com/questions/41418586/removing-white-space-from-image-on-webpage - Poorna Senani Gamage
1个回答

5
你可以用for循环来完成,但这样会比较麻烦。
from PIL import Image, ImageChops

def getbox(im, color):
    bg = Image.new(im.mode, im.size, color)
    diff = ImageChops.difference(im, bg)
    diff = ImageChops.add(diff, diff, 2.0, -100)
    return diff.getbbox()

def split(im):
    retur = []
    emptyColor = im.getpixel((0, 0))
    box = getbox(im, emptyColor)
    width, height = im.size
    pixels = im.getdata()
    sub_start = 0
    sub_width = 0
    offset = box[1] * width
    for x in range(width):
        if pixels[x + offset] == emptyColor:
            if sub_width > 0:
                retur.append((sub_start, box[1], sub_width, box[3]))
                sub_width = 0
            sub_start = x + 1
        else:
            sub_width = x + 1
    if sub_width > 0:
        retur.append((sub_start, box[1], sub_width, box[3]))
    return retur

这使得像这样检索图像中的裁剪框变得容易:

im = Image.open("/home/einfochips/Documents/imagecomparsion/kroger_image_comparison/SnapshotImages/screenshot_Hide.png")

for idx, box in enumerate(split(im)):
    im.crop(box).save("trim_{0}.png".format(idx))

如果您已经知道要提取的图像大小,可以选择使用以下方式:
def split(im, box):
    retur = []
    pixels = im.getdata()
    emptyColor = pixels[0]
    width, height = im.size;
    y = 0;
    while y < height - box[3]:
        x = 0
        y_step = 1
        while x < width - box[2]:
            x_step = 1
            if pixels[y*width + x] != emptyColor:
                retur.append((x, y, box[2] + x, box[3] + y))
                y_step = box[3] + 1
                x_step = box[2] + 1
            x += x_step
        y += y_step
    return retur

添加另一个参数到调用中

for idx, box in enumerate(split(im, (0, 0, 365, 150))):
    im.crop(box).save("trim_{0}.png".format(idx))

@ N0b1ts 这就是我想要的... 但问题在于,裁剪后的图像尺寸为 364150,它应该是 365150,因为这才是图像的实际尺寸。 我的任务是将所有图像与基准图像进行比较,并使它们相等。 请帮忙。 - Sachhya
1
抱歉,忘记了一个偏移量 :) 现在已经进行了更正。 - N0b1ts
1
如果图像的第一行中有背景像素,则此解决方案仍将失败。 - N0b1ts
第二种解决方案处理所有像素,但需要您知道要提取的图像的大小。 - N0b1ts
1
从您的解决方案中,我可以匹配修剪基本图像中的图像。图像的大小因图像而异。 - Sachhya

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接