Reputation: 161
Say I have a 2D RGB array that is show as:
[[[ 0. 0. 0.5]
[ 0.5 0. 0.5]
[ 0. 0. 0.5]
...,
[ 0.5 0. 0.5]
[ 0. 0. 0.5]
[ 0. 0. 0.5]]]
I want to add the individual elements in the R
and B
columns to the G
part of the array so it looks like:
[[[ 0. 0.5 0.5]
[ 0.5 1.0 0.5]
[ 0. 0.5 0.5]
...,
[ 0.5 1.0 0.5]
[ 0. 0.5 0.5]
[ 0. 0.5 0.5]]]
What would be the easiest way to approach this problem?
Upvotes: 0
Views: 398
Reputation: 879143
You could use
arr[...,1] = arr[...,0] + arr[...,2]
or perhaps more readably,
R, G, B = arr[...,0], arr[...,1], arr[...,2]
G[:] = R + B
Since G
is a basic slice of arr
, it is a view. Modifying a view modifies the original array. The
assignment G[:] = ...
modifies G
inplace. So the assignment modifies arr
.
import numpy as np
arr = np.array([[[ 0., 0., 0.5],
[ 0.5, 0., 0.5],
[ 0., 0., 0.5],
[ 0.5, 0., 0.5],
[ 0., 0., 0.5],
[ 0., 0., 0.5]]])
R, G, B = arr[...,0], arr[...,1], arr[...,2]
G[:] = R + B
print(arr)
yields
[[[ 0. 0.5 0.5]
[ 0.5 1. 0.5]
[ 0. 0.5 0.5]
[ 0.5 1. 0.5]
[ 0. 0.5 0.5]
[ 0. 0.5 0.5]]]
Upvotes: 1
Reputation: 504
I would convert your list of lists in an numpy.array
, and then slice it.
import numpy as np
a=np.array([[ 0. , 0. , 0.5],
[ 0.5, 0. , 0.5],
[ 0. , 0. , 0.5]])
a[:,1] += a[:,0] + a[:,2]
print(a)
Output :
array([[ 0. , 0.5, 0.5],
[ 0.5, 1. , 0.5],
[ 0. , 0.5, 0.5]])
Upvotes: 2