簡體   English   中英

使用Python圖像庫模塊反轉圖像

[英]Inverting image using the Python Image Library module

我對學習如何使用python image libary模塊反轉圖像(使圖像為負)感興趣。

但是,我不能使用ImageOps函數“反轉”。 我需要使用RGB值的另一種解決方案。 我已搜索並嘗試無濟於事。

只需從255(或最大值)中減去每個RGB值即可獲得新的RGB值。 這篇文章告訴您如何從圖片中獲取RBG值。

一種明顯的方法是使用Image.getpixel和Image.putpixel,對於RGB,每個都應該是三個整數的元組。 您可以得到(255-r,255-g,255-b),然后放回去。

或者使用pix = Image.load(),它看起來更快。

或者,如果您查看ImageOps.py,則它使用查找表(lut列表)將圖像映射到反向圖像。

或者,如果這不違反您的分配規則,則可以使用Numpy。 然后,您可以使用更快的矩陣運算。

如果您正在使用media模塊,則可以執行以下操作:

import media
def invert():
    filename = media.choose_file()    # opens a select file dialog
    pic = media.load_picture(filename)    # converts the picture file into a "picture" as recognized by the module.
    for pixel in pic:
        media.set_red(pixel, 255-media.get_red(pixel))    # the inverting algorithm as suggested by @Dingle
        media.set_green(pixel, 255-media.get_green(pixel))
        media.set_blue(pixel, 255-media.get_blue(pixel))
print 'Done!'

如果您使用的是picture模塊,則過程類似,如下所示:

import picture
def invert():
    filename = picture.pick_a_file()    # opens a select file dialog
    pic = picture.make_picture(filename)    # converts the picture file into a "picture" as recognized by the module.
    for pixel in picture.get_pixels(pic):
        picture.set_red(pixel, 255-picture.get_red(pixel))    # the inverting algorithm as suggested by @Dingle
        picture.set_green(pixel, 255-picture.get_green(pixel))
        picture.set_blue(pixel, 255-picture.get_blue(pixel))
print 'Done!'

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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