【问题标题】:Using PIL or a Numpy array, how can I remove entire rows from an image?使用 PIL 或 Numpy 数组,如何从图像中删除整行?
【发布时间】:2017-04-05 14:30:23
【问题描述】:

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

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

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

【问题讨论】:

    标签: python image-manipulation python-imaging-library


    【解决方案1】:

    我为您编写了以下代码,该代码删除了完全黑色的每一行。我使用for 循环中的else clause,该循环将在循环被中断退出时执行。

    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")
    

    如果您有任何问题,尽管问:)

    【讨论】:

    • 感谢您花时间回答halex。我想我应该对我给出的例子更具体一点,因为我之前尝试过类似的东西。任何行都可能以黑色像素开头,因此某些不打算删除的行是。这就是为什么我需要知道如何只删除完全黑色的行(颜色不重要,仅作为示例),甚至是完全透明的行。
    • @Py-Newbie 我更改了代码以删除完全黑色的行。如果要删除透明的行,则不能将图像转换为 RGB,而是转换为 RGBA
    • 再次感谢您的帮助,它运行良好。我还有一个问题要问您,是否可以修改您编写的代码以查找全黑列(而不是像以前那样的行),裁剪列之间的内容并从中制作新图像。可以在此处找到示例图像postimage.org/image/bh8or7yzn。从该样本中,目标是获得 10 个单独的图像。我希望这些细节足以让您理解我的意思。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-27
    • 2018-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多