Here is my code:
JavaScript
x
7
1
# 'a' is a 3D array which is the RGB data
2
a = np.array([[[1, 2, 3], [4, 5, 6]], [[4, 5, 6], [1, 2, 3]]])
3
# I want to do some calculate separately on R, G and B
4
np.apply_along_axis(lambda r, g, b: r * 0.5 + g * 0.25 + b * 0.25, axis=-1, arr=a)
5
6
# my target output is: [[1.75, 4.75], [4.75, 1.75]]
7
But the above way will give me error, missing 2 required positional arguments.
I have tried to do like this:
JavaScript
1
2
1
np.apply_along_axis(lambda x: x[0] * 0.5 + x[1] * 0.25 + x[2] * 0.25, axis=-1, arr=a)
2
It works but every time when I need to do computation on the array element, I need to type the index, it is quite redundant. Is there any way that I can pass the array axis as multi iuputs to the lambda when using np.apply_along_axis?
Advertisement
Answer
apply_along_axis
is slow and unnecessary:
JavaScript
1
7
1
In [279]: a = np.array([[[1, 2, 3], [4, 5, 6]], [[4, 5, 6], [1, 2, 3]]])
2
In [280]: r,g,b = a[ ,0],a[ ,1],a[ ,2]
3
r * 0.5 + g * 0.25 + b * 0.25 :
4
Out[280]:
5
array([[1.75, 4.75],
6
[4.75, 1.75]])
7
or
JavaScript
1
5
1
In [281]: a.dot([0.5, 0.25, 0.25])
2
Out[281]:
3
array([[1.75, 4.75],
4
[4.75, 1.75]])
5
or
JavaScript
1
5
1
In [282]: np.sum(a*[0.5, 0.25, 0.25], axis=2)
2
Out[282]:
3
array([[1.75, 4.75],
4
[4.75, 1.75]])
5