How to determine if a certain color surrounds a specific point in an array?

2 views (last 30 days)
The function I am trying to create recieves an image, the position of a pixel denoted by its row and column position, and a specified color. The goal is to determine if the specified point is surrounded by the specified color meaning it has the color on all sides including the diagonals. If the specified point is on the edge, the points outside the array can be considered the required color. I am stuck on how to determine if a point on the edge is considered surrounded in a short concise way. Any help would be appreciated.
img = 'Image17.tif';
p1 = [1, 10];
myColor = [255 0 0];
myImg = imread(img);
redArr = myImg(:, :, 1);
greenArr = myImg(:, :, 2);
blueArr = myImg(:, :, 3);
isColor = (redArr == myColor(1)) & (greenArr == myColor(2)) & (blueArr == myColor(3));
row = p1(1);
col = p1(2);
areaArr = isColor(row-1:row+1, col-1:col+1);
if sum(areaArr, 'all') == 8
myValue = true;
end
if sum(areaArr, 'all') < 8
myValue = false;
end

Accepted Answer

Image Analyst
Image Analyst on 28 Mar 2021
Since your areaArr is 9 pixels, not 8, you'll need to extract just the 8 neighbors, not a 3x3 square.
areaArr = isColor(row-1:row+1, col-1:col+1);
areaArr = areaArr(:); % Turn into column vector.
areaArr(5) = []; % Delete middle one.
To determine if the pixels is on the edge, check if the row or column is at the limits
[rows, columns, numColorChannels] = size(myImg)
if row == 1
% It's on the left edge
end
if row == rows
% It's on the right edge
end
if col == 1
% It's on the top edge
end
if col == columns
% It's on the bottom edge
end
That's basically it, however you'll also have to check if the pixel is exactly in one of the 4 corners. That's just adding 4 additional if blocks, which I assume you can figure out.

More Answers (1)

darova
darova on 28 Mar 2021
Try to add some tolerance
tol = 10;
red1 = abs(double(redArr) - myColor(1))) < tol;
blue1 = abs(double(greenArr) - myColor(2)) < tol;
green1 = abs(double(blueArr) - myColor(3)) < tol;
isColor = red1 & blue1 & green1;

Community Treasure Hunt

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

Start Hunting!