Reputation: 21
I have a binary image that includes some objects. The shape of these objects is irregular.
The object that is in centre of this image is important for me. How can I remove all the objects that are not connected to my central object? The desired result should look like:
Upvotes: 1
Views: 719
Reputation: 837
A simple thing you could do without the img-toolbox is put a seed in the middle. Then step one to the right,left,up,down and repeat the values of each gridpoint. You have to do it in a way, such that after reaching the black region everything else gets to be 0 aswell, whereas everything connected with the seed stays 1.
I guess your pic is defined as p(n rows,m cols) = [ 0 0 0 1 0 1; 0 1 0 0 1; ...]
.
Now what I mean is the following:
Start in the middle [x,y] = [n/2, m/2]
, or where you want to "keep" the ornament.
for k = 1:n/2-1
for i = 1:m/2-1
p(x+k,y+j) = p(x+k,y+j)*p(x+k-1,y+j-1);
end
end
.. repeat with the other 1/2 of the picture
By multiplying a value with it's neighbor you get 1*1 at first. After reaching the first 0, everything will be multiplied with 0,... so everything left is the connected inner piece. I don't see, if my indices are correct here,.. I leave that for you to try it out (if you need -1 or +1 somewhere so that your shape is not altered).
Upvotes: 0
Reputation: 104474
If you have the image processing toolbox, a simple call to bwareaopen
will do the trick. Basically you filter out those regions that fall below a certain threshold for area. I choose a threshold of 700 pixels and I managed to get the centre region. This is coupled with the fact that the centre region is the largest region in your image. First, I read your image directly from StackOverflow and converted your image to binary as it's originally in grayscale. Next, I call bwareaopen
with the threshold of 700 pixels and then display the image:
im = im2bw(imread('http://s2.img7.ir/tQ69Q.jpg'));
out = bwareaopen(im, 700);
imshow(out);
We get:
Alternatively, you can use regionprops
and work on the Area
field and determine which object is the largest object in your image. From there, you can simply create a new image and use the PixelIdxList
field to determine the pixel locations (in column-major) that belong to the largest object and set the proper locations in the output image.
Something like this:
im = im2bw(imread('http://s2.img7.ir/tQ69Q.jpg'));
s = regionprops(im, 'Area', 'PixelIdxList');
[~,maxID] = max([s.Area]);
pix = s(maxID);
out = false(size(im));
out(pix.PixelIdxList) = true;
imshow(out);
We should get the same thing like we did before. However, the disadvantage is that only one object will be extracted overall. You can adjust the above code to search for objects that surpass an area of a certain threshold, but then you'd basically be doing bwareaopen
, so stick with that method instead.
Upvotes: 2