Py-*_*bie 5 python image-manipulation python-imaging-library
我想知道如何从图像中删除整行,最好是基于行的颜色?
示例:我有一个高度为 5 像素的图像,顶部两行和底部两行是白色,中间行是黑色。我想知道如何让 PIL 识别这一行黑色像素,然后删除整行并保存新图像。
我对python有一些了解,并且到目前为止一直通过列出“getdata”的结果来编辑我的图像,因此任何带有伪代码的答案可能就足够了。谢谢。
我给你写了下面的代码,它删除了每一行完全是黑色的。我使用循环的else 子句,for当循环没有被中断退出时将被执行。
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")
Run Code Online (Sandbox Code Playgroud)
如果你有问题就问:)