使用 PIL 或 Numpy 数组,如何从图像中删除整行?

Py-*_*bie 5 python image-manipulation python-imaging-library

我想知道如何从图像中删除整行,最好是基于行的颜色?

示例:我有一个高度为 5 像素的图像,顶部两行和底部两行是白色,中间行是黑色。我想知道如何让 PIL 识别这一行黑色像素,然后删除整行并保存新图像。

我对python有一些了解,并且到目前为止一直通过列出“getdata”的结果来编辑我的图像,因此任何带有伪代码的答案可能就足够了。谢谢。

hal*_*lex 7

我给你写了下面的代码,它删除了每一行完全是黑色的。我使用循环的else 子句for当循环没有被中断退出时将被执行。

from PIL import Image

def find_rows_with_color(pixels, width, height, color):
    rows_found=[]
    for y in xrange(height):
        for x in xrange(width):
            if pixels[x, y] != color:
                break
        else:
            rows_found.append(y)
    return rows_found

old_im = Image.open("path/to/old/image.png")
if old_im.mode != 'RGB':
    old_im = old_im.convert('RGB')
pixels = old_im.load()
width, height = old_im.size[0], old_im.size[1]
rows_to_remove = find_rows_with_color(pixels, width, height, (0, 0, 0)) #Remove black rows
new_im = Image.new('RGB', (width, height - len(rows_to_remove)))
pixels_new = new_im.load()
rows_removed = 0
for y in xrange(old_im.size[1]):
    if y not in rows_to_remove:
        for x in xrange(new_im.size[0]):
            pixels_new[x, y - rows_removed] = pixels[x, y]
    else:
        rows_removed += 1
new_im.save("path/to/new/image.png")
Run Code Online (Sandbox Code Playgroud)

如果你有问题就问:)

  • @Py-Newbie 我更改了代码以删除完全黑色的行。如果要删除透明的行,则不得将图像转换为 RGB,而是转换为 `RGBA`。 (2认同)
  • 再次感谢您的帮助,它完美地工作。我还有一个问题要问您,是否可以修改您编写的代码以查找全黑列(而不是像以前那样的行),裁剪列之间的内容并从中制作新图像。可以在此处找到示例图像 http://postimage.org/image/bh8or7yzn。从该样本中,目标是获得 10 个单独的图像。我希望这些细节足以让您明白我的意思。 (2认同)