how to index 3D array with 2D array ?

5 次查看(过去 30 天)
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);

采纳的回答

Stephen23
Stephen23 2017-1-17
编辑:Stephen23 2017-1-17
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 个评论
Jan
Jan 2017-1-17
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
Stephen23 2017-1-17
编辑:Stephen23 2017-1-17
@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

请先登录,再进行评论。

更多回答(0 个)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by