Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the content of the array in python

I have a multidimensional array(let's call it 'data'), I print it produce like this

[[[255, 255, 255]
  [255, 255, 255]
  [0, 0, 0]
  [255, 255, 255]]
 [[0, 0, 0]
  [255, 255, 255]
  [0, 0, 0]
  [0, 0, 0]]
  ... and so on
  [255, 255, 255]]]

i want to change the content of data like this

[[1,
  1,
  0,
  1]
 [0,
  1,
  0,
  0]
  ... and so on
  1]]

[255, 255, 255] become 1, and [0, 0, 0] become 0

I'm trying with numpy.where, but I'm desperate How to do that in python programming?

like image 244
ircham Avatar asked Aug 08 '26 16:08

ircham


1 Answers

One way is checking whether a value is 255, and reducing the boolean result with np.logical_and

np.logical_and.reduce(a==255, axis=2).view('i1') 

For the following example:

a = np.array([[[255, 255 ,255],
               [255, 255, 255],
               [0 ,0, 0],
               [255, 255 ,255]],
              [[0 ,0, 0],
               [255, 255 ,255],
               [0 ,0, 0],
               [0 ,0, 0]]])

np.logical_and.reduce(a==255, axis=2).view('i1') 

array([[1, 1, 0, 1],
       [0, 1, 0, 0]], dtype=int8)
like image 179
yatu Avatar answered Aug 11 '26 06:08

yatu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!