2

I have an image stored in a 2D numpy array. I want to extract all pixel values in a rectangle from that array. The rectangle is defined as ((x1,y1),(x2,y2)) where all x and y s are naturally array indices.

I can extract the pixel values using a nested for loop, but what would be a pythonic way to do this?

2 Answers 2

2

Just use slicing. For example:

In [3]: a = numpy.arange(20).reshape((4,5))

In [4]: a
Out[4]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

In [5]: a[2:4, 3:5]
Out[5]: 
array([[13, 14],
       [18, 19]])

In general, you can replace an index with a slice where slices have the form start:stop or, optionally, start:stop:step and variables are allowed:

In [6]: x=2 ; print a[x-1:x+1, :]
[[ 5  6  7  8  9]
 [10 11 12 13 14]]
Sign up to request clarification or add additional context in comments.

Comments

2

Take a look at numpy's indexing.

import numpy
array = numpy.arange(24).reshape((4, 6))
indices = ((1, 3), (2, 5))

((x1, y1), (x2, y2)) = indices
result = array[x1:x2, y1:y2]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.