Segmentation of foreground from background
<p>I'm currently working on a project that uses a <em>Lacatan Banana</em>, and I would like to know how to further separate the foreground from the background:</p>

<p><img src="https://i.stack.imgur.com/XNwX6.jpg" alt=""></p>

<p>I already got a segmented image of it using erosion, dilation, and thresholding only. The problem is that it is still not properly segmented.</p>

<p>Here is my code:</p>

<pre><code>    cv::Mat imggray, imgthresh, fg, bgt, bg;
    cv::cvtColor(src, imggray, CV_BGR2GRAY); //Grayscaling the image from RGB color space
    cv::threshold(imggray, imgthresh, 0, 255, CV_THRESH_BINARY_INV | CV_THRESH_OTSU); //Create an inverted binary image from the grayscaled image
    cv::erode(imgthresh, fg, cv::Mat(), cv::Point(-1, -1), 1); //erosion of the binary image and setting it as the foreground
    cv::dilate(imgthresh, bgt, cv::Mat(), cv::Point(-1, -1), 4); //dilation of the binary image to reduce the background region
    cv::threshold(bgt, bg, 1, 128, CV_THRESH_BINARY); //we get the background by setting the threshold to 1
    cv::Mat markers = cv::Mat::zeros(src.size(), CV_32SC1); //initializing the markers with a size same as the source image and setting its data type as 32-bit Single channel
    cv::add(fg, bg, markers); //setting the foreground and background as markers                                                                
    cv::Mat mask = cv::Mat::zeros(markers.size(), CV_8UC1);
    markers.convertTo(mask, CV_8UC1);    //converting the 32-bit single channel marker to a 8-bit single channel
    cv::Mat mthresh;
    cv::threshold(mask, mthresh, 0, 255, CV_THRESH_BINARY | CV_THRESH_OTSU); //threshold further the mask to reduce the noise
    // cv::erode(mthresh,mthresh,cv::Mat(), cv::Point(-1,-1),2);
    cv::Mat result;
    cv::bitwise_and(src, src, result, mthresh);  //use the mask to subtrack the banana from the background
    for (int x = 0; x &lt; result.rows; x++) { //changing the black background to white
        for (int y = 0; y &lt; result.cols; y++) {
            if (result.at&lt;Vec3b&gt;(x, y) == Vec3b(0, 0, 0)){
                result.at&lt;Vec3b&gt;(x, y)[0] = 255;
                result.at&lt;Vec3b&gt;(x, y)[1] = 255;
                result.at&lt;Vec3b&gt;(x, y)[2] = 255;
            }
        }
    }
</code></pre>

<p>This is my result:</p>

<p><img src="https://i.stack.imgur.com/FZyC9.jpg" alt=""></p>