Numpy.putmask公司有图像吗

2024-04-26 20:19:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个图像转换成具有RGBA值的ndarray。假设它是50×50×4。在

我想用array([255, 255, 255, 255])的值array([255, 255, 255, 255])替换所有像素。所以:

from numpy import *
from PIL import Image
def test(mask):
        mask = array(mask)
        find = array([255, 255, 255, 255])
        replace = array([0, 0, 0, 0])
        return putmask(mask, mask != find, replace)

mask = Image.open('test.png')
test(mask)

我做错什么了?这给了我一个ValueError: putmask: mask and data must be the same size。但是如果我把数组改成数字(find=255,replace=0),它就可以工作了。在


Tags: fromtest图像imageimportnumpypilmask
3条回答

一个更简洁的方法是

img = Image.open('test.png')
a = numpy.array(img)
a[(a == 255).all(axis=-1)] = 0
img2 = Image.fromarray(a, mode='RGBA')

更一般地说,如果findrepl的项目不完全相同,您也可以这样做

^{pr2}$

实现这种通道掩蔽的一种方法是将阵列分割为r、g、b、a通道,然后使用numpy逻辑位操作定义索引:

import numpy as np
import Image

def blackout(img):
    arr = np.array(img)
    r,g,b,a=arr.T
    idx = ((r==255) & (g==255) & (b==255) & (a==255)).T
    arr[idx]=0
    return arr

img = Image.open('test.png')
mask=blackout(img)
img2=Image.fromarray(mask,mode='RGBA')
img2.show()

这个解决方案使用putmask,我认为它最接近于OPs代码。原始代码中有两个错误,操作员应该知道:1)putmask是一个就地操作。它返回None。2) putmask还需要大小相等的数组。它(太糟糕了)没有axis关键字参数。在

import numpy as np
from PIL import Image

img1 = Image.open('test.png')
arry = np.array(img1)
find = np.array([255, 255, 255, 255])
repl = np.array([  0,   0,   0,   0])
# this is the closest to the OPs code I could come up with that
# compares each pixel array with the 'find' array
mask = np.all(arry==find, axis=2)
# I iterate here just in case repl is not always the same value
for i,rep in enumerate(repl):
    # putmask works in-place - returns None
    np.putmask(arry[:,:,i], mask, rep)

img2 = Image.fromarray(arry, mode='RGBA')
img2.save('testx.png')

相关问题 更多 >