简体   繁体   中英

How do I replace pixels that meet a distance criteria?

I have the image:

A = [3 1 1 2 2
     0 0 0 3 2
     0 0 3 3 2
     1 1 1 1 2
     1 1 1 2 2];

From the image I obtained the following matrix:

B = [1,1; 3,3; 2,4; 3,4];

Now, I want to test the distances between each pixel in 'B' to see which ones are greater than 1 when compared to the immediate pixel in the next row. For pixels that have distances <= 1 between them, I would want to replace both locations in 'A' with a NaN , otherwise, I would leave them as they are.

My expected output would be:

A = [3 1 1   2   2
     0 0 0   NaN 2
     0 0 NaN NaN 2
     1 1 1   1   2
     1 1 1   2   2];

I have tried the following code, but i can't quite understand what exactly i am doing wrong.

[row, col] = find(A==3);
B          = [row col]

for k = size(B, 1)-1
    if sqrt( (row(k,:) - (row(k+1,:)))^.2 + (col(k,:) - (col(k+1,:)))^.2 ) <= 1
       A(B(k, :)) = NaN
    end 
end

Please any help on this is greatly appreciated. Many thanks!

If I understood your question correctly, you want to change neighboring 3 cells to NaN . The easiest way is to check all 3 cells and check if one of its neighbors are 3 , as done in the code below:

for k = 1:length(row)
    if safeCheck(A, row(k)+1, col(k)) || safeCheck(A, row(k), col(k)+1) || ...
            safeCheck(A, row(k)-1, col(k)) || safeCheck(A, row(k), col(k)-1)
        A(row(k), col(k)) = NaN;
    end
end

function b = safeCheck(A, row, col)
    if (1 <= row && row <= size(A, 1) && 1 <= col && col <= size(A, 2))
        b = A(row, col) == 3 || isnan(A(row, col));
    else
        b = false;
    end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM