Make background of binary image all black
Show older comments
Hi,
Im trying to segment an image of an apple such that i can extract the boundary of the apple, but i first need to make all the background of the binary image black, and am not sure on how to do this.
The test photo is this:

the resultant output is this:

The code:
a = imread('q2.jpg');
b=rgb2gray(a);
bw = imbinarize(b);
bw2 = imcomplement(bw);
c =imfill(bw2,'holes');
imshow(c)
Accepted Answer
More Answers (1)
Parth Dethaliya
on 23 Dec 2020
This process totally depends upon the specfic image so it is really hard to generalize the method, but i am showing you the approach to tackle such situations.
By running a function "bwareafilt" on the final image you obtained yo may get this results,
% c is your final image (After filling holes)
largest = bwareafilt(c,1); % This command yeilds first largest component
imshow(largest);

largest = bwareafilt(c,2); % This command yeilds first two largest components
imshow(largest);

So it is obvious that the region you are interested is second largest, now simply subtracting those two results you can achieve the goal.
largest = bwareafilt(c,2) - bwareafilt(c,1) ;
imshow(largest);

1 Comment
Finn Hartley
on 23 Dec 2020
Categories
Find more on Convert Image Type in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
