I am trying to understand the following Python segment.
def upsample_filt(size):
factor = (size + 1) // 2
if size % 2 == 1:
center = factor - 1
else:
center = factor - 0.5
og = np.ogrid[:size, :size]
return (1 - abs(og[0] - center) / factor) * \
(1 - abs(og[1] - center) / factor)
According to numpy, ogrid returns a mesh-grid ndarrys with only one dimension.I think the program want to generatesize*sizearray. Why is it be written asog = np.ogrid[:size, :size]Or what does:size` mean?
As a test, I setup size=4, and print((1 - abs(og[0] - center) / factor)*(1 - abs(og[1] - center) / factor)), the output is as follows:
[[ 0.0625 0.1875 0.1875 0.0625]
[ 0.1875 0.5625 0.5625 0.1875]
[ 0.1875 0.5625 0.5625 0.1875]
[ 0.0625 0.1875 0.1875 0.0625]]
I am not very clear how does (1 - abs(og[0] - center) / factor)*(1 - abs(og[1] - center) / factor) fillup this multi-dimensional array?
Lets make it simpler:
In [264]: og=np.ogrid[:3,:2]
In [265]: og
Out[265]:
[array([[0],
[1],
[2]]), array([[0, 1]])]
The shape of these 2 is (3,1) and (1,2). They are 2d; 'o' for 'open'.
In [266]: og[0]*og[1]
Out[266]:
array([[0, 0],
[0, 1],
[0, 2]])
They broadcast together to form a (3,2) array
(3,1), (1,2) => (3,2), (3,2) => (3,2)
Look at what mgrid produces:
In [271]: np.mgrid[:3,:2]
Out[271]:
array([[[0, 0],
[1, 1],
[2, 2]],
[[0, 1],
[0, 1],
[0, 1]]])
2 (3,2) arrays, that produce the same combination
ogrid and mgrid are class objects with unique indexing method. [:3, :2] looks to Python as regular indexing.
meshgrid produces the same thing, but with a regular function syntax
In [275]: np.meshgrid(np.arange(3), np.arange(2),sparse=True,indexing='ij')
Out[275]:
[array([[0],
[1],
[2]]), array([[0, 1]])]
Another way of performing the same calculation - by using [:,None] to turn the 1st range into a (3,1) array. Here the broadcasting is (3,1),(2,) => (3,1),(1,2) => (3,2)
In [276]: np.arange(3)[:,None]*np.arange(2)
Out[276]:
array([[0, 0],
[0, 1],
[0, 2]])
===================
(1 - abs(og[0] - center) / factor) *
(1 - abs(og[1] - center) / factor)
this just scales the 2 ranges and them multiplies them together
In [292]: a=(1-abs(np.arange(4)-1.5)/2)
In [293]: a[:,None]*a
Out[293]:
array([[ 0.0625, 0.1875, 0.1875, 0.0625],
[ 0.1875, 0.5625, 0.5625, 0.1875],
[ 0.1875, 0.5625, 0.5625, 0.1875],
[ 0.0625, 0.1875, 0.1875, 0.0625]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With