簡體   English   中英

PIL中是否有Image.point()方法,允許您一次操作所有三個通道?

[英]Is there an Image.point() method in PIL that allows you to operate on all three channels at once?

我想寫一個基於每個像素的紅色,綠色和藍色通道的點濾波器,但看起來這可能達不到point()的能力 - 它似乎在一個像素中運行一次一個通道。 我想做這樣的事情:

def colorswap(pixel):
    """Shifts the channels of the image."""
    return (pixel[1], pixel[2], pixel[0])
image.point(colorswap)

是否有一種等效方法可以讓我使用一個濾波器,它接收一個3元組的RGB值並輸出一個新的3元組?

根據迄今為止的回復,我猜答案是'不'。

但你總是可以使用numpy來有效地完成這種工作:

def colorswap(pixel):
    """Shifts the channels of the image."""
    return (pixel[1], pixel[2], pixel[0])

def npoint(img, func):
    import numpy as np
    a = np.asarray(img).copy()
    r = a[:,:,0]
    g = a[:,:,1]
    b = a[:,:,2]
    r[:],g[:],b[:] = func((r,g,b))
    return Image.fromarray(a,img.mode)

img = Image.open('test.png')
img2 = npoint(img, colorswap)
img2.save('test2.png')

額外:看起來Image類不是只讀的,這意味着你可以讓你的新npoint函數更像point (不推薦除非像混淆人一樣):

Image.Image.npoint = npoint

img = Image.open('test.png')
img2 = img.npoint(colorswap)

您可以使用load方法快速訪問所有像素。

def colorswap(pixel):
    """Shifts the channels of the image."""
    return (pixel[1], pixel[2], pixel[0])

def applyfilter(image, func):
    """ Applies a function to each pixel of an image."""
    width,height = im.size
    pixel = image.load()
    for y in range(0, height):
        for x in range(0, width):
            pixel[x,y] = func(pixel[x,y])

applyfilter(image, colorswap)

暫無
暫無

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

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