问题
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