I don't understand the process of putting the array in the index position of the array in Numpy. (Example> 3d_array[2d_array])

Asked 2 years ago, Updated 2 years ago, 116 views

During the image processing process using numpy, there is a part of the code that I don't understand, so I'm posting a question.

import numpy as np
image = np.array([[[1,1,1],[1,1,1]],[[1,1,1],[1,1,1]]])
b = np.array([[True,True],[True,False]])

image[b] = [0,0,0]

It's a code like this. image is data with RGB values of 1,1,1 in an image with a resolution of 2*2. b is a 2*2 dimensional array with True and False values.

I don't quite understand what it means to put [b] in question 1> image. I know you put image [0,0,0], but I don't know if you put an array.

If you put in question 2> image[b] = [0,0,0], the result comes out like this, but why is this?

array([[[0, 0, 0],
        [0, 0, 0]],

       [[0, 0, 0],
        [1, 1, 1]]])

numpy python image-processing

2022-09-21 21:03

1 Answers

I think you're talking about the advanced index of numpy.

Unlike Python, the array of numpy can be indexed as a sequence object (except for tuples). This is called advanced indexing.

There are integrer array indexing and boolean array indexing in advanced indexing, and the question is boolean array indexing.

numpy Official Document - Boolean array indexing reads:

If obj.ndim == x.ndim, x[obj] returns a one-dimensional array filled with the elements of x responding to the True values of obj. .. (hereinafter omitted)

Briefly interpreted

If obj.ndim == x.ndim, x[obj] brings elements of x that match the true value to one-dimensional obj. I think you'll get a better idea if you run the following code.

import numpy as np
image = np.array([[[1,1,1],[1,1,1]],[[1,1,1],[1,1,1]]])

b = np.array([[True,True],[True,False]])
print(image[b])

b = np.array([[True,True],[True,True]])
print(image[b])


2022-09-21 21:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.