Steven Lu
Steven Lu

Reputation: 43427

Is it possible to multiply a 3x3 matrix (a color transformation) with a rank 3 tensor/3D matrix (a color image)?

When images are read in, they are converted into matrices/tensors of dimension (x,y,3) where the last one is for the R, G, B channels.

I am looking to apply a colorspace conversion, so that's a 3x3 matrix that I want to apply to each pixel. So what I'm sort of looking to do here is a "component wise" matrix-vector multiply.

Can this be done with matlab/octave? I'm using octave but it seems like if there's a way with matlab I should have a fighting chance with octave.

I'm just getting something like this:

octave:15> B
B =

   0.9465229   0.2946927  -0.1313419
  -0.1179179   0.9929960   0.0073716
   0.0923046  -0.0464579   0.9946464

octave:16> B * Y
error: invalid conversion of NDArray to Matrix

I guess I just gotta do a nested for loop manually. But even when I try this:

Blena = lena; %// copy the structure -- here lena is a rgb image of type double
for i=1:rows(lena)
  for j=1:columns(lena)
    Blena(i,j) = B * lena(i,j,:);
  endfor
endfor

lena(i,j,:) is still an NDArray.

Upvotes: 3

Views: 2106

Answers (1)

Luis Mendo
Luis Mendo

Reputation: 112669

Sure. You just need some reshapeing:

im = rand(100,150,3); %// example "image"
T = rand(3,3); %// example transform matrix
result = reshape((T * reshape(im, [], 3).').', size(im));

This basically arranges the original image into a 3-row matrix (each row is a color component, each column is a pixel), does the matrix multiplication, and then puts back into shape.

Upvotes: 2

Related Questions