简体   繁体   中英

python numpy ndArray replace values in first n-1 columns based on value in nth column

I have an ndArray of shape (800x1280x4) - An image data of 4 channels. In the 4rth channel ie, alpha channel some values are 1 (transparent) and some are 255 (opaque). I want to replace the r,g,b channel values with zero, where alpha channel value is 1.

To illustrate this I took an example array as below and tried following code:

>>> import numpy as np
>>>
>>> a = np.random.randint(255, size=(3,5,4))
>>> a
array([[[165, 200,  80, 149],
        [247, 126,  88,   2],
        [ 35,  24,  59, 167],
        [105,  69,  98,  78],
        [138, 224,  50,  32]],

       [[ 90,  53, 113,  39],
        [105, 153,  60, 101],
        [139, 249, 105,  79],
        [171, 127,  81, 240],
        [133,  22,  62, 172]],

       [[197, 163, 253,  62],
        [193,  57, 208, 247],
        [241,  80, 100, 249],
        [181, 118,  72,  52],
        [221, 121,  89, 138]]])
>>> # I want to replace cell values with zero where 4th column value is < 100
>>> b = np.where(a[...,-1]<100,0,a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<__array_function__ internals>", line 6, in where
ValueError: operands could not be broadcast together with shapes (3,5) () (3,5,4)

I get the ValueErrors. what is the approach for replacing first three cell values based on 4rth cell value in numpy ndArray?

Try this

a[np.where(a[...,-1]<100)] = np.array([0,0,0,100])

This will perform in-place operation upon a

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM