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 image
img = imread('example_image.jpg');

% Get the mouse input (x,y position)
[x, y] = ginput(1);

% Define the intensity threshold
threshold = 50;

% Define the maximum number of pixels to be added in each direction
max_pixels = 10;

% Get the intensity value at the mouse position
intensity_value = img(x,y);

% Define a mask with the same size as the image
mask = false(size(img));

% Create a queue with the mouse position as the starting point
queue = [x, y];

% Loop through the queue
while ~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 threshold
    if abs(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];
    end
end

% Display the result
imshow(img);
hold on;
imshow(mask);
1610 chars
50 lines

gistlibby LogSnag