How to check 4 neighbor connectivity in grayscale image!!
Show older comments
matrix =
147 155 139 104 84 139
136 134 99 73 60 144
98 82 60 54 47 118
86 59 46 48 38 90
88 66 50 44 35 67
88 75 53 40 43 48
p = matrix(3,3)
q = matrix(2,5)
V = {1:60}
Accepted Answer
More Answers (1)
Ahmad
on 19 Mar 2023
0 votes
clc;
clear all;
matrix1 = [147 155 139 104 84 139; 136 134 99 73 60 144; 98 82 60 54 47 118; 86 59 46 48 38 90; 88 66 50 44 35 67; 88 75 53 40 43 48];
V = {1:50};
binary_matrix = [147 155 139 104 84 139; 136 134 99 73 60 144; 98 82 60 54 47 118; 86 59 46 48 38 90; 88 66 50 44 35 67; 88 75 53 40 43 48];
binary_matrix(binary_matrix > 60) = 0;
binary_matrix(binary_matrix <= 50 & binary_matrix >= 1) = 1;
L = bwlabel(binary_matrix,4);
[r, c] = find(L==1);
rc = [r c];
imshow(L);
1 Comment
It's good to post answers, but try to post answers which:
- address the specific needs of the OP or the general needs of future readers
- produce correct results for either of those two objectives
- are documented well enough to communicate your methods and intent.
- are formatted
To improve:
% the given array (assumed to be integer-valued)
matrix = [147 155 139 104 84 139;
136 134 99 73 60 144;
98 82 60 54 47 118;
86 59 46 48 38 90;
88 66 50 44 35 67;
88 75 53 40 43 48];
% don't need a cell array (op's mistake)
% 60, not 50
V = 1:60;
% test point coordinates
p = [3 3]; % assumed to be [y x]
q = [2 5];
% create the logical image without overwriting the thing you're testing
% use the specific values of V instead of literals
% as it's not clear that V always a fully-populated linear series
% i'm treating it as an arbitrary set of discrete values
mask = ismember(matrix,V);
% label the image
L = bwlabel(mask,4);
% check to see if points p,q belong to the same blob
areconnected = L(p(1),p(2)) == L(q(1),q(2))
% show the label array and mark the points
imshow(L,[]); hold on
plot([p(2) q(2)],[p(1) q(1)],'x','linewidth',3,'markersize',10)
% i don't know why this was included
[r, c] = find(L==1);
rc = [r c];
There is only one blob. If p and q are both members of the foreground, they are connected.
Categories
Find more on Data Import and Analysis in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!