To solve this problem you need to separate background and foreground. This is ththe solution, I propose you:
- convert the image from Rgb to grayscale; You will obtain an image that we call I1
- apply a morphological filter, erosion using a large radius, eventually several times ==> you should erase the pill by erosion and obtain only the background; You will obtain a new image I2
- Substract I2 to I1, you will obtain the foreground i.e the pill;
- apply another morphological filter to fill any hole in the pill that you obtained;
- apply a morphological filter, erosion, small radius to remove any isolated pixel.
1) convert the image from Rgb to grayscale; You will obtain an image that we call I1
;
2) apply a morphological filter, erosion using a large radius, eventually several times
==> you should erase the pill by erosion and obtain only the background;
You will obtain a new image I2
;
3) subtract I2
to I1
, you will obtain the foreground i.e the pill;
4) apply another morphological filter to fill any hole in the pill that you obtained;
5) apply a morphological filter, erosion, small radius to remove any isolated pixel.
This method does not require any threshold, shape drtectiondetection, color segmentation or anything else.