简体   繁体   中英

how to extract line in images(3bands) using numpy in python?

In order to modify the value of a particular vertical line in the image, i want to extract the 3-band vertical line of the image.

When I was a two dimensional array, I extracted the vertical lines with the following code:

vertical_line = array[:,[1]]

I tried to use this code in a 3d array image but it failed.

#image shape(b,g,r) (100,100,3)
# my try
vertical_line_try_1 = image[:,[1]][3]#result => [[255,255,255]]
vertical_line_try_2 = image[:,[1][3]]#result => IndexError: list index out of range
vertical_line_try_3 = image[:,[1],[3]]#result => IndexError: index 3 is out of bounds for axis 2 with size 3

How can I extract the vertical lines of three bands at once without writing a loop?

When you index with a slice the corresponding dimension is kept (since you get a possible stridded range of values). On the other hand, when you index with a single number that dimension disappears.

Ex:

a = np.random.randn(4,5)

# Let's get the third column in the matrix
print(a[:, 2].shape)   # prints `(4,)` -> we get a vector
print(a[:, 2:3].shape) # prints `(4,1)` -> we keep the result as a column matrix

From your two dimensional example it seems you are using advanced indexing just as a way to keep the dimension. If that is true, using a slice containing a single element as I have shown is cleaner (my opinion) and faster (tested with %timeit in IPython).

Now, back to your question. It looks like you want to extract all values whose index of the second dimension is equal to 1, similar to the red part in the figure below.

索引第二个维度

If that is the case, then just use either image[:,1, :] (or just image[:,1] ) if you to get the values as a matrix, or image[:,1:2, :] if you want a 3D array.


It is also useful to understand what your failed attempts were actually doing.

  1. image[:,[1]][3] : This is actually two indexing operations in the same line. First, image[:,[1]] would return a 100x1x3 array, and then the second indexing with [3] would take the fourth line. Since this second indexing is a regular one (not a fancy and not a slice), then the indexed dimension disappears and you get a 1x3 array in the end
  2. image[:,[1][3]] : This one I'm not really sure what it is doing
  3. image[:,[1],[3]] : This means "take all values from the first dimension, but only the ones from the second index of the first dimension and the fourth index of the third dimension. Since the third dimension only has "size" 3, then trying to get the fourth index results in the out of bound error.

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