python - 从图像中删除所有空白区域

标签 python opencv image-processing imagemagick python-imaging-library

我需要从图像中删除所有空白,但我不知道该怎么做...... 我正在使用修剪功能来修剪边框的空白区域,但图像中间仍然存在空白区域我附上了要从中删除空白区域的原始图像

original Image

我的代码

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 文件中,那就太好了。

最佳答案

你可以用 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))

关于python - 从图像中删除所有空白区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49126955/

相关文章:

python - 从 win32evtlog.EvtQuery 结果中获取一个事件对象

image-processing - 旋转图像中的脸

android - android中的自由手字符识别

python - 如何判断图像是否暗?

iphone - 不使用捏合/UIScrollView 缩小照片

python - 如何使用 Python 子进程执行长 bash 序列

python - 内部函数未形成闭包

c# - Windows 操作系统中无法访问的 IP 套接字关闭时间

c++ - OpenCV:阈值和反转图像

opencv - 根据图片确定物体的体积