Matlab: replace values in one matrix with another matrix according to their referenced locations

StackOverflow https://stackoverflow.com/questions/20998881

  •  25-09-2022
  •  | 
  •  

質問

I have two geotiff images (saying "A" and "B") imported in Matlab as matrices with Geotiffread. One has different values, while the second has only 0 and 255s. What I'd like to do is replacing all the 255s with the values inside the other image (or matrix), according to their positions. A and B differs in size, but they have the same projections.

I tried this:

A (A== 255)= B;

the output is the error:

??? In an assignment  A(:) = B, the number of elements in A and B must be the same.

Else, I also tried with the logical approach:

if A== 255
    A= B;
end

and nothing happens.

Is there a way to replace the values of A with values of B according to a specific value and the position in the referenced space?

役に立ちましたか?

解決 2

It seems to me that you are trying to mask an image with a binary mask. You can do this:

BW = im2bw(B,0.5);
A=A.*BW;

hope it helps

他のヒント

As darthbith put in his comment, you need to make sure that the number of entries you want to replace is the same as the number values you are putting in.

By doing A(A==255)=B you are trying to put the entire matrix B into the subset of A that equals 255.

However, if, as you said, the projections are the same, you can simply do A(A==255) = B(A==255), under the assumption that B is larger or the same size as A.

Some sample code to provide a proof of concept.

A = randi([0,10],10,10);
B = randi([0,4],15,15);

C = A % copy original A matrix for comparison later
A(A==5) = B(A==5); % replace values
C==A % compare original and new

This example code creates two matrices, A is a 10x10 and B is a 15x15 and replaces all values that equal 5 in A with the corresponding values in B. This is shown to be true by doing C==A which shows where the new matrix and the old matrix vary, proving replacement did happen.

Try A(A==255) = B(A==255). The error is telling you that when you try to assign values to the elements of an array, you cannot give it any more or fewer values than you are trying to assign.

Also, regarding the if statement: if A==255 means the same as if all(A==255), as in, if any elements of A are not 255, false is returned. You can check this at the command line.

If you're really desperate, you can use a pair of nested for loops to achieve this (assuming A and B are the same size and shape):

[a,b] = size(A);
for ii = 1:a
    for jj = 1:b
        if A(ii,jj) == 255
            A(ii,jj) = B(ii,jj);
        end
    end
end
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top