How to create binary image mask if my data image have multiple lesion in 1 image?
Show older comments
My question is, how can I create binary mask if my image data have multiple lesion in 1 image?
Below I shared examole of my single lesion (already in binary mask);

According to the codes I wrote, it is drawn by free hand.
Below I shared my multiple lesion image data:

Answers (1)
Milan Bansal
on 9 Sep 2024
Hi Dayangku Nur Faizah Pengiran Mohamad
I understand that you wish to select multiple lesions in a single image using drawfreehand and save the final mask as binary image. You might also want to save a binary mask for individual lesions.
Please refer to the following steps to achieve this.
- Manual Lesion Selection: Each time you use drawfreehand, you manually outline a lesion in the image.
- Binary Mask Creation: The binary mask for the lesion is created with createMask.
- Saving Individual Lesions: Each lesion is saved as a separate binary image.
- Combining Masks: The current lesion mask is added to a final combined mask using a logical OR (|), allowing for multiple lesion regions to be merged.
- Stopping Condition: After drawing a lesion, you are prompted whether to continue or stop. If you enter 'n', the loop breaks, and the process stops.
Please refer to following code snippet for implementation:
% Read the image
img = imread('lp.png');
% Display the image
imshow(img);
hold on; % Hold on to allow multiple drawings
% Initialize the combined mask
[rows, cols, ~] = size(img);
combinedMask = false(rows, cols); % Binary mask initialized to all false
% Loop to allow manual drawing of multiple lesions
while true
% Manually select a lesion using drawfreehand
h = drawfreehand('Color', 'r');
% Create binary mask for the selected lesion
lesionMask = createMask(h);
% Save the individual lesion mask as a binary image
% Remove this step if you do not wish to save mask for each lesion.
imwrite(lesionMask, ['lesion_' num2str(lesionCount) '.png']);
% Add the current lesion mask to the combined mask
combinedMask = combinedMask | lesionMask;
% Ask user if they want to select another lesion
cont = input('Do you want to select another lesion? (y/n): ', 's');
if strcmpi(cont, 'n')
break; % Exit the loop if no more lesions to draw
end
end
% Display the final combined mask
figure;
imshow(combinedMask);
title('Final Combined Mask for All Lesions');
% Optionally, save the combined mask
imwrite(combinedMask, 'combined_lesion_mask.png');
Please refer to the following documentation to learn more:
- drawfreehand: https://www.mathworks.com/help/images/ref/drawfreehand.html
- createMask: https://www.mathworks.com/help/images/ref/imroi.createmask.html
Hope this helps!
Categories
Find more on Build Interactive Tools in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!