3

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.

Steven Lu
  • 41,389
  • 58
  • 210
  • 364

1 Answers1

2

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.

Luis Mendo
  • 110,752
  • 13
  • 76
  • 147
  • Whoa. That's neat. Also solves the second issue i had – Steven Lu Aug 18 '14 at 23:12
  • Could you explain a bit what's going on with the period and the single quote (edit: I see it is non-conjugate transpose. Now learning about what that actually is.)? Also, this generates an image that is shredded and interleaved – Steven Lu Aug 18 '14 at 23:19
  • The period followed by single quote is just [matrix transpose](http://stackoverflow.com/q/25150027/2586922). And sorry, there was a transpose missing, hence the shredding. See edited answer – Luis Mendo Aug 18 '14 at 23:25
  • Ah, yeah I was trying to figure out where to stick the second transpose as it clearly needed one somewhere. – Steven Lu Aug 18 '14 at 23:26
  • 1
    Alternatively: `result = reshape((reshape(im, [], 3) * T.'), size(im));` (single transpose, but on the transformation matrix) – Luis Mendo Aug 18 '14 at 23:28