Changing color of pixels around certain pixels

22 views (last 30 days)
So I have an image named "0001.tif". I managed to import the image and do basic manupulations and save it.
What I am strugeling with is that when a pixel (that satisfies a certain criteria) is detected, the pixels in a 5 pixel radius should become white. In other words, these surrounding pixels' RGB values should change to 255.
Note: There can be more than one set of white pixels in the original image.
img = imread(append('0001.tif'));
R = img(:,:,1);
G = img(:,:,2);
B = img(:,:,3);
RGB = sqrt(im2double(R).^2+im2double(G).^2+im2double(B).^2);
idx = RGB<0.3;
R(idx) = 255;
G(idx) = 255;
B(idx) = 255;
imgNew(:,:,1) = R;
imgNew(:,:,2) = G;
imgNew(:,:,3) = B;
Is there any way to acomplish this while using vectorization and without having to run through a nested for loop?

Accepted Answer

Steve Eddins
Steve Eddins on 11 Jan 2022
Suppose mask is a logical matrix that indicates which pixels satisfy your condition. (That seems to be the purpose of idx in your code.) Then dilate mask using a circular structuring element with radius 5. Use the dilated mask to set the red, green, and blue component values to 255. It might look something like this:
se = strel('disk',5,0);
dilated_mask = imdilate(mask,se);
R(dilated_mask) = 255;
G(dilated_mask) = 255;
B(dilated_mask) = 255;
imgNew = cat(3,R,G,B);
Note that strel and imdilate are in Image Processing Toolbox.
  1 Comment
Image Analyst
Image Analyst on 11 Jan 2022
@Edrich Engelbrecht Note that instead of
R = img(:,:,1);
G = img(:,:,2);
B = img(:,:,3);
you can do
[R, G, B] = imsplit(img);
and instead of
imgNew(:,:,1) = R;
imgNew(:,:,2) = G;
imgNew(:,:,3) = B;
you can do
imgNew = cat(3, R, G, B):

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!