使用PIL或Numpy数组,如何从图像中删除整行? [英] Using PIL or a Numpy array, how can I remove entire rows from an image?

查看:113
本文介绍了使用PIL或Numpy数组,如何从图像中删除整行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to know how I could remove entire rows from an image, preferably based on the color of the row?

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

Example: I have an image that is 5 pixels in height, the top two rows and the bottom two rows are white and the middle row is black. I would like to know how I could get PIL to identify this row of black pixels, then, remove the entire row and save the new image.

我对python有一定的了解,并且到目前为止,我一直在通过列出"getdata"的结果来编辑图像,因此,任何带有伪代码的答案都有望满足.谢谢.

I have some knowledge of python and have so far been editing my images by listing the result of "getdata" so any answers with pseudo code may hopefully be enough. Thanks.

推荐答案

我为您编写了以下代码,该代码删除了全黑的每一行.我使用 else子句for循环中的,如果循环不是中断而退出,则将执行该循环.

I wrote you the following code that removes every row which is completely black. I use the else clause of the for loop that will be executed when the loop is not exited by a break.

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

如果您有任何疑问,请问:)

If you have questions just ask :)

这篇关于使用PIL或Numpy数组,如何从图像中删除整行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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