valentin
valentin

Reputation: 1123

How to assign values to image in matlab

I have 5 columns x, y, r, g, b with values of line number, column number, red, green and blue. The lines of this n by 5 matrix are not in a particular order, however they are consistent with image(x,y) and the r,g,b.

I would like to do something like I=uint8(zeros(480,640,3) and just change those rgb values based on the n by 5 mat.

Something along the lines of I(mat(:,1), mat(:,2), 1)=mat(:,3) for red etc

Upvotes: 2

Views: 110

Answers (2)

Luis Mendo
Luis Mendo

Reputation: 112659

The following uses the concept of linear indexing and the versatile bsxfun function:

m = 640; %// number of rows
n = 480; %// number of columns
I = zeros(m, n, 3, 'uint8'); %// initiallize directly as uint8
I(bsxfun(@plus, x(:)+(y(:)-1)*m, (0:2)*m*n)) = [r(:) g(:) b(:)]; %// fill values

Small example: for

m = 2;
n = 3;
x = [1 2 1];
y = [1 1 2];
r = [ 1  2  3];
g = [11 12 13];
b = [21 22 23];

the code produces

I(:,:,1) =
    1    3    0
    2    0    0

I(:,:,2) =
   11   13    0
   12    0    0

I(:,:,3) =
   21   23    0
   22    0    0

Upvotes: 2

Cape Code
Cape Code

Reputation: 3574

An alternative:

INDr = sub2ind([480, 640, 3], mat(:, 1), mat(:,2), ones([numel(mat(:,3)), 1]));
INDg = sub2ind([480, 640, 3], mat(:, 1), mat(:,2), 2*ones([numel(mat(:,3)), 1]));
INDb = sub2ind([480, 640, 3], mat(:, 1), mat(:,2), 3*ones([numel(mat(:,3)), 1]));

I=uint8(zeros(480,640, 3));

I(INDr)=mat(:,3);
I(INDg)=mat(:,4);
I(INDb)=mat(:,5);

Note that in Matlab, the convention between axes is different between images and arrays.

Upvotes: 1

Related Questions