Using PIL or a Numpy array, how can I remove entire rows from an image?

馋奶兔 提交于 2020-05-29 04:13:12

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/12770218/using-pil-or-a-numpy-array-how-can-i-remove-entire-rows-from-an-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!