Using a PIL or a Numpy array, how can I remove whole lines from an image?

I would like to know how to remove whole lines from an image, preferably based on the color of the line?

Example: I have an image with a height of 5 pixels, the top two lines and the bottom two lines are white and the middle line is black. I would like to know how I could get a PIL to define this row of black pixels, then delete the entire row and save the new image.

I have some knowledge of python and am still editing my images listing the result of "getdata", so any answers with pseudo-code may be enough. Thanks.

+4
source share
1 answer

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

+3
source

Source: https://habr.com/ru/post/1438271/


All Articles