Richard
Richard

Reputation: 3414

How to measure mean in region of numpy array

Fairly new to using numpy, and I've got a piece of code where I've got a 2D array (image) where I want to calculate the mean and stddev of a square region with the array. So +/- a certain delta in rows and cols around a specific point

Right now my code looks like this (for an arbitary region of 20 pixel size around (100, 100)):

r = 100
c = 100
r0 = r - 10
r1 = r + 10
c0 = c - 10
c1 = c + 10
mean = image[r0:r1, c0:c1].mean()
std = image[r0:r1, c0:c1].std()

Question

Is there a more concise, or more numpy'ish/python'ish, way of calculating the slice to feed into mean() and std(), that doesn't take up so many lines? (I know I could do it with numpy.where(), but the conditions then would take almost as many lines)

thanks!

Upvotes: 0

Views: 884

Answers (2)

lxop
lxop

Reputation: 8615

Not that I'm aware of, and I would be a little surprised if there were. What you have is very simple, so a special function for it wouldn't help much. My suggestion for readability would be to do the +/- inline to create a region array, then call the mean and std methods on that variable.

Also, in case you're wondering, the slicing that you've done there is pretty efficient, numpy shouldn't be creating a new array, just making a new view of the existing memory. Using something like where would make a new array.

Upvotes: 1

yasi
yasi

Reputation: 547

you can use these 2 tutorial: numpy-mean, numpy-std

Upvotes: 0

Related Questions