how to index 3D array with 2D array ?
6 views (last 30 days)
Show older comments
i have a colored image 100x100x3 and a logical matrix 100x100. how do i keep the values of those at which the logical matrix is 1 and set the those at 0 to 0 ?
I would imagine it something like this but it doesnt work.
image_a;
image_b;
map;
image_b = image_a(map);
0 Comments
Accepted Answer
Stephen23
on 17 Jan 2017
Edited: Stephen23
on 17 Jan 2017
Method one create a new image:
image_b = bsxfun(@times,double(map),image_a)
or on newer MATLAB versions with implicit array expansion:
image_b = double(map) .* image_a;
The most generalized method is probably:
bsxfun(@times, image_a, cast(map,class(image_a)));
Method two change original image:
image_a(~map(:,:,[1,1,1])) = 0
4 Comments
Jan
on 17 Jan 2017
Applying a mask to an RGB image is a common task. I'm still astonished, that you need to create a large temporary array for this:
idx = cat(3, map, map, map);
"image_a(map, 1:3)" would contain enough information to be interpreted correctly.
Stephen23
on 17 Jan 2017
Edited: Stephen23
on 17 Jan 2017
@Jan Simon: on MATLAB R2012b I get something quite different:
>> A = randi(9,2,3,2)
A(:,:,1) =
7 5 9
3 7 9
A(:,:,2) =
5 2 8
2 3 3
>> X = [true,false,false;false,true,true]
X =
1 0 0
0 1 1
>> A(X,1:2) = 0
A(:,:,1) =
0 0 9
3 7 9
0 0 0
0 0 0
0 0 0
0 0 0
A(:,:,2) =
5 2 8
2 3 3
0 0 0
0 0 0
0 0 0
0 0 0
But this works (I know, there is still a large intermediate variable):
>> A = randi(9,2,3,2)
A(:,:,1) =
7 5 3
7 1 9
A(:,:,2) =
2 5 1
8 9 4
>> X = [true,false,false;false,true,true]
X =
1 0 0
0 1 1
>> A(X(:,:,[1,1])) = 0
A(:,:,1) =
0 5 3
7 0 0
A(:,:,2) =
0 5 1
8 0 0
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!