我想知道如何从图像中删除整行,最好是根据行的颜色?
示例:我有一个高度为 5 像素的图像,顶部两行和底部两行是白色,中间行是黑色。我想知道如何让 PIL 识别这一行黑色像素,然后删除整行并保存新图像。
我对 python 有一些了解,并且到目前为止一直在通过列出“getdata”的结果来编辑我的图像,因此任何带有伪代码的答案可能就足够了。谢谢。
我写了下面的代码,删除了每一行全黑的行。我用else 子句 http://docs.python.org/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops of the for
循环时将执行的循环not休息退出。
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")
如果您有疑问,请询问:)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)