簡體   English   中英

使用PIL或Numpy數組,如何從圖像中刪除整行?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM