Change the content of the array in python

Viewed 86

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?

3 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)

try this one:

data = [
    [
        [255, 255, 255],
        [255, 255, 255],
        [0, 0, 0],
        [255, 255, 255]
    ],
    [
        [0, 0, 0],
        [255, 255, 255],
        [0, 0, 0],
        [0, 0, 0],
    ],
    [
        [255, 255, 255],
        [255, 255, 255],
        [0, 0, 0],
        [0, 0, 0],
    ]
]

result = [[1 if y == [255, 255, 255] else 0 for y in x] for x in data]
print(result)

Bare in mind that it will work if the only possible values are [255, 255, 255] or [0, 0, 0] (This is what I understand from the question)

This is how I would do it:

Using tuple(col) == (255, 255, 255) is important because the truth value of an array with more than one element is ambiguous.

data = np.asarray(im) # (assuming this is how you got your data)

new_data = np.array(np.zeros((len(data),len(data[0]))))

for x,row in enumerate(data):
    for y,col in enumerate(row):
        if tuple(col) == (255, 255, 255):
            new_data[x][y] = 1

print(new_data)

Or in one line:

new_data = [[1 if tuple(col) == (255, 255, 255) else 0 for col in row] for row in data]

The first will result in a numpy array and the second, just a list. However, you can convert it to a numpy array by using:

new_data = np.array([[1 if tuple(col) == (255, 255, 255) else 0 for col in row] for row in data])
Related