5

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

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.

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.

4

1 回答 1

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

如果您有问题,请询问:)

于 2012-10-07T16:47:55.973 回答