oma11
oma11

Reputation: 55

How to find a pixel using a previously found pixel index in Matlab

i have a point 'A' in a matrix, and i have been able to search for a particular pixel value (say ‘30’) around the 8-connected neighborhood of 'A' (with value ‘00’). The 'find' function returns an index (say of '1') of that pixel value of interest around point 'A'.

Now the issue is that i need to find exactly another pixel (of the same value) which is connected to the initial pixel value of ‘30’ using the returned index information from the 1st search. The 2nd pixel value of ‘30’ is not in the immediate neighborhood of ‘A’ but in it’s next immediate neighborhood.

The code so far:

img = [20 20 20 20 20 20 20;
       20 30 20 20 20 20 20;
       20 20 30 20 20 20 20;
       40 40 10 00 20 20 20;
       40 40 10 40 40 40 40;
       40 10 10 40 40 40 40;
       10 10 10 40 40 40 40] 

[Arow, Acol]     = find(img==00)
AIdx             = sub2ind(size(img), Arow, Acol);
M                = size(img, 1);
neighbor_offsets = [-M-1, -M, -M+1, -1, 1, M-1, M, M+1];

%Compute index array of the immediate neighbors of ‘A’
Aneighbors       = bsxfun(@plus, AIdx, neighbor_offsets);

%search for pixel value of ‘30’ in the immediate neighbors of ‘A’
find(img(Aneighbors)==30)

the last line of the code returns an index of 1. Is it possible to use this information to find the other 30?

I know I can easily find this 2nd pixel value by creating another index array of the next immediate neighbours of ‘A’ (where the 2nd ‘30’ resides) as follows:

    neigh_Aneighbor_offsets = [(-2*M)-2, (-2*M)-1, (-2*M), (-2*M)+1,(-2*M)+2, -M-2, -M+2, -2, 2, M-2, M+2, (2*M)-2, (2*M)-1, (2*M), (2*M)+1, (2*M)+2];

%Compute index array of the 2nd immediate neighbors of ‘A’
neigh_Aneighbors        = bsxfun(@plus, Aidx, neigh_Aneighbor_offsets);

%Search for the 2nd pixel value of ‘30’ in the next immediate neighborhood of ‘A’
find(img(neigh_Aneighbors)==30)

However, I would only want to find this by assuming that I know nothing else except the location of the 1st ‘30’ that I have already found. In any case, I have no idea how to go about this. Any help/suggestion/advice is duly appreciated.

Upvotes: 0

Views: 73

Answers (1)

rahnema1
rahnema1

Reputation: 15867

Just save result of find to a variable f and obtain proper Aidx from Aneighbors(f):

f=find(img(Aneighbors)==30)
Aidx = Aneighbors(f)
Aneighbors=bsxfun(@plus, Aidx, neighbor_offsets)
f=find(img(Aneighbors)==30)

Upvotes: 1

Related Questions