I wrote you the following code that removes every line that is completely black. I use the else clause of the for loop, which will be executed when the loop does not end with 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 :)
source share