gpt4 book ai didi

python - 在Python中更改像素颜色: How to do it faster?

转载 作者:行者123 更新时间:2023-12-01 05:40:46 27 4
gpt4 key购买 nike

我有一个 RGB 图像,并尝试将 RGB 上的每个像素设置为黑色,其中相应的 alpha 像素也为黑色。所以基本上我试图将 Alpha“烘焙”到我的 RGB 中。我已经尝试使用 PIL 像素访问对象、PIL ImageMath.eval 和 numpy 数组:

PIL 像素访问对象:

def alphaCutoutPerPixel(im):    pixels = im.load()    for x in range(im.size[0]):        for y in range(im.size[1]):            px = pixels[x, y]            r,g,b,a = px            if px[3] == 0:  # If alpha is black...                pixels[x,y] = (0,0,0,0)    return im

PIL ImageMath.eval:

def alphaCutoutPerBand(im):    newBands = []    r, g, b, a = im.split()    for band in (r, g, b):        out = ImageMath.eval("convert(min(band, alpha), 'L')", band=band, alpha=a)        newBands.append(out)    newImg = Image.merge("RGB", newBands)    return newImg

Numpy array:

def alphaCutoutNumpy(im):    data = numpy.array(im)    r, g, b, a = data.T    blackAlphaAreas = (a == 0)    # This fails; why?    data[..., :-1][blackAlphaAreas] = (0, 255, 0)    return Image.fromarray(data)

The first method works fine, but is really slow. The second method works fine for a single image, but will stop after the first when asked to convert multiple. The third method I created based on this example (first answer): Python: PIL replace a single RGBA colorBut it fails at the marked command:

data[..., :-1][blackAlphaAreas] = (0, 255, 0, 0)
IndexError: index (295) out of range (0<=index<294) in dimension 0

Numpy 似乎对这类东西很有希望,但我并没有真正了解如何一步设置数组部分的语法。有什么帮助吗?也许还有其他想法可以快速实现我上面描述的目标?

干杯

最佳答案

这不使用高级索引,但更容易阅读,恕我直言:

def alphaCutoutNumpy(im):
data = numpy.array(im)
data_T = data.T
r, g, b, a = data_T
blackAlphaAreas = (a == 0)
data_T[0][blackAlphaAreas] = 0
data_T[1][blackAlphaAreas] = 0
data_T[2][blackAlphaAreas] = 0
#data_T[3][blackAlphaAreas] = 255
return Image.fromarray(data[:,:,:3])

关于python - 在Python中更改像素颜色: How to do it faster?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17615025/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com