i've made some search but didn't find the exact same questions - and the solutions I found were not adaptable.
I have an Image, represented by a numpy array of shape (l1,l2,3)
where l1,l2 are integers and three because RGB.
And for reasons, I want to change the basis, it means applying a matrix P to all the RGB vectors. Please note that P
has a shape of (3,3)
.
I've written this:
def change_base(Image,P):
Image_copie=np.zeros(Image.shape)
for i in range(Image_copie.shape[0]):
for j in range(Image_copie.shape[1]):
Image_copie[i,j]=np.dot(P,Image[i,j])
return Image_copie
It works, obviously, but it's ugly and extremely slow.
Do you guys have any solution, using numpy maybe ? I don't use opencv ..!
Thanks !
You are reducing the last axis on the two inputs
Image
andP
. So, you can usenp.tensordot
, like so -This can also be expressed as
np.dot
with some reshaping before and after it, like so -One can also use
np.einsum
for such a reduction operation, like so -For performance, being a solely reduction operation, with no axis-alignment requirement,
dot-based
solutions would be faster for large arrays, but for small to decent size arrays,einsum
might be better.Runtime test
Case #1 :
Case #2 :