how to index 3D array with 2D array ?

조회 수: 3 (최근 30일)
RuiQi
RuiQi 2017년 1월 17일
편집: Stephen23 2017년 1월 17일
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개)

카테고리

Help CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by