簡體   English   中英

更改像素透明背景

[英]Change pixels transparent background

我有幾張不同的圖像,我想將圖像的每個透明像素更改為不同的顏色。

我找到了一種提取圖像透明像素的所有RGB值的方法,如下所示:

data[data[:,:,3]==0,:3][0]

現在,當我嘗試為該像素分配不同的數組時,它將不起作用:

data[data[:,:,3]==0,:3][0] = np.array([255,0,255])

print(data[data[:,:,3]==0,:3][0])
Out[1]: [0 0 0]

如何更改此像素?

雖然矢量化操作可能適用於我要實現的目標,但我發現可以使用的解決方案如下。

for h in range(0,data.shape[0]):
    for w in range(0,data.shape[1]):
        if data[h, w][3] == 0:
            data[h, w] = np.random.randint(0,255), np.random.randint(0,255), np.random.randint(0,255), 255

它遍歷圖像中的每個像素,然后檢查該像素是否透明,如果是透明的,則將該像素的RGB值隨機化。 可能會比較慢,但是可以正常工作!

更新的答案

我從您的評論中看到,您需要的靈活性比我從您的問題中了解的更多。 嘗試這個:

In [85]: im = np.array(Image.open('image.png').convert('RGBA'))

In [86]: for x in np.argwhere(im[:,:,3]==0):
    ...:     im[x[0],x[1],:]=np.random.randint(0,255), np.random.randint(0,255), np.random.randint(0,255), np.random.randint(0,255)

原始答案

我想你的意思是:

In [32]: im = np.array(Image.open('image.png').convert('RGBA'))

In [33]: im
Out[33]: 
array([[[126, 126, 126, 255],        <--- grey pixel
        [126, 126, 126, 255],
        [126, 126, 126, 255],
        [126, 126, 126, 255],
        [126, 126, 126, 255]],

       [[126, 126, 126, 255],
        [255,   0,   0,   0],        <--- transparent pixel
        [255,   0,   0,   0],        <--- transparent pixel
        [255,   0,   0,   0],        <--- transparent pixel
        [126, 126, 126, 255]],

       [[126, 126, 126, 255],
        [126, 126, 126, 255],
        [126, 126, 126, 255],
        [126, 126, 126, 255],
        [126, 126, 126, 255]]], dtype=uint8)

In [34]: im[im[:,:,3]==0]=(1,2,3,4)

In [35]: im
Out[35]: 
array([[[126, 126, 126, 255],
        [126, 126, 126, 255],
        [126, 126, 126, 255],
        [126, 126, 126, 255],
        [126, 126, 126, 255]],

       [[126, 126, 126, 255],
        [  1,   2,   3,   4],
        [  1,   2,   3,   4],
        [  1,   2,   3,   4],
        [126, 126, 126, 255]],

       [[126, 126, 126, 255],
        [126, 126, 126, 255],
        [126, 126, 126, 255],
        [126, 126, 126, 255],
        [126, 126, 126, 255]]], dtype=uint8)

樣本圖片

它是一排三個透明的紅色像素,周圍是一個不透明的灰色邊框,寬度為一個像素。 很小...

在此處輸入圖片說明

暫無
暫無

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

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