[英]Using PIL or a Numpy array, how can I remove entire rows from an image?
我想知道如何从图像中删除整行,最好是根据行的颜色?
示例:我的图像高度为5像素,前两行和后两行为白色,中间行为黑色。 我想知道如何让PIL识别这一行黑色像素,然后删除整行并保存新图像。
我对python有一些了解并且到目前为止通过列出“getdata”的结果来编辑我的图像所以任何伪代码的答案都可能足够。 谢谢。
我给你写了以下代码,删除了完全黑色的每一行。 我使用for
循环的else子句 ,当循环没有被中断退出时将执行。
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")
如果你有问题就问:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.