expand selection in image to include all pixels from x, y by 20 pixels in both axes in matlab

To expand a selection in an image to include all pixels from x, y by 20 pixels in both axes in MATLAB, you can use the imdilate function from the Image Processing Toolbox. Here's an example code:

main.m
% Load the image
img = imread('my_image.jpg');

% Define the selection rectangle
x = 100;
y = 150;
width = 50;
height = 70;

% Create a binary mask of the selection
mask = false(size(img, 1), size(img, 2));
mask(y:y+height, x:x+width) = true;

% Expand the mask by 20 pixels in both axes
se = strel('square', 40); % 20 pixels in each direction
mask_expanded = imdilate(mask, se);

% Apply the mask to the image
img_selected = bsxfun(@times, img, cast(mask_expanded, class(img)));

% Show the result
figure;
imshow(img_selected);
529 chars
24 lines

In this code, we first load the image using the imread function. Then, we define the selection rectangle by specifying its top-left corner (x and y coordinates) and its width and height (width and height variables, respectively).

Next, we create a binary mask of the selection using the false function to create a matrix of the same size as the image, and then set the corresponding pixels to true in the selection rectangle.

To expand the mask, we use the strel function to create a structuring element of a square shape with a size of 40x40 pixels (20 pixels in each direction), and then apply it to the mask using imdilate.

Finally, we apply the mask to the original image using element-wise multiplication with bsxfun. The resulting image, img_selected, will have all pixels inside the expanded selection set to their original values, and all other pixels set to 0. We can then display the result using the imshow function.

gistlibby LogSnag