How to use loops to scan through pixels and black out the pixels outside a shape with a (white) perimeter (image)

5 ビュー (過去 30 日間)
Ahmad
Ahmad 2022 年 11 月 21 日
編集済み: Abhaya 2025 年 1 月 27 日
I am attempting to use loops to check each pixel for whether or not its within a perimeter of white. Essentially I want to keep whats inside the white perimeter while blacking out everything else. I would like to do this using a loops rather than a mask if possible so I can apply this to other similar images (Different skin colors with same white perimeter). Below I have an image listed for example. In my attempt to loop through I found I could not make the loop skip over the area between the white lines and everything but the white parts would be blacked out. Below is the code I used to try and do this:
newI =(imread(nameF));
figure;
imshow(newI);
newB = newI(:,:,1);
for r = 1:size(newB,1)
for c = 1:size(newB,2)
pixel = newB(r,c);
current = c;
if pixel == 255
for cc = current:size(newB,2)
pixel2=(newB(r,cc));
if pixel2 == 255
skip = cc;
break
end
end
else
newI(r, c, 1) = 0;
newI(r, c, 2) = 0;
newI(r, c, 3) = 0;
end
c = skip;
end
end
figure
imshow(newI)

回答 (1 件)

Abhaya
Abhaya 2025 年 1 月 23 日
編集済み: Abhaya 2025 年 1 月 27 日
Hi Ahmad,
As per my understanding, you want to retain only the area within the white perimeter in the image, while blacking out everything outside of it. Additionally, you want this process to be applied to multiple images with varying skin tones, as long as they have the white perimeter.
To achieve this, you can use MATLAB 'imfill' function. For a detailed workflow please refer to the steps given below:
  • Step 1: Read the image using MATLAB 'imread' function.
img=imread('image.jpg');
  • Step 2: FInd out all the pixels with pure white value.
BW = all(img == 255, 3); % Detect pure white pixels
  • Step 3: You can use image dilation to close small gaps in the perimeter. To achieve this you can use MATLAB 'imdilate' function.
SE = strel('disk', 5); % Structuring element for dilation
BW_dilated = imdilate(BW, SE);
  • Step 4: Fill holes inside the dilated region to ensure all areas inside the boundary are covered, using MATLAB 'imfill' function.
BW_filled = imfill(BW_dilated, 'holes');
  • Step 5: Set pixels outside the mask to black.
newImg = img;
newImg(repmat(~BW_filled, [1, 1, 3])) = 0;
You can visualize the processed image as shown below.
For more information on MATLAB 'imdilate' and 'imfill' functions, please refer to the documentations linked below.
Hope this solves your query.

カテゴリ

Help Center および File ExchangeImage Processing Toolbox についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by