with image size of 512x512 start at x,y position from mouse input then add adjacent pixels within 50 intensity value up to a maximum of 10 pixels in each direction in matlab
main.m
% Read the imageimg = imread('example_image.jpg');
% Get the mouse input (x,y position)[x, y] = ginput(1);
% Define the intensity thresholdthreshold = 50;
% Define the maximum number of pixels to be added in each directionmax_pixels = 10;
% Get the intensity value at the mouse positionintensity_value = img(x,y);
% Define a mask with the same size as the imagemask = false(size(img));
% Create a queue with the mouse position as the starting pointqueue = [x, y];
% Loop through the queuewhile ~isempty(queue)
% Get the current pixel from the queue current_pixel = queue(1, :);
% Remove the current pixel from the queue queue(1, :) = [];
% Check if the current pixel is within the intensity thresholdifabs(img(current_pixel(1), current_pixel(2)) - intensity_value) <= threshold
% Add the current pixel to the mask mask(current_pixel(1), current_pixel(2)) = true;
% Get the neighboring pixels within the maximum number of pixels in each direction x_range = max(1, current_pixel(1) - max_pixels):min(size(img, 1), current_pixel(1) + max_pixels);
y_range = max(1, current_pixel(2) - max_pixels):min(size(img, 2), current_pixel(2) + max_pixels);
[X, Y] = meshgrid(y_range, x_range);
neighbors = [X(:), Y(:)];
% Remove the neighbors already in the mask neighbors(all(mask(sub2ind(size(mask), neighbors(:,1), neighbors(:,2)))', 2), :) = [];
% Enqueue the remaining neighbors queue = [queue; neighbors];
endend% Display the resultimshow(img);
hold on;
imshow(mask);