Cleaning a segmented image in Opencv <p>I have this original:</p> <p><a href="https://i.stack.imgur.com/BFvgZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BFvgZ.jpg" alt="enter image description here"></a></p> <p>After segmentation I obtained this image:</p> <p><a href="https://i.stack.imgur.com/91A9h.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/91A9h.jpg" alt="enter image description here"></a></p> <p>As you can see it is still not perfectly segmented. Any suggestions on how to further "clean" this segmented image? Here is my code:</p> <pre><code>using namespace cv; using namespace std; Mat COLOR_MAX(Scalar(65, 255, 255)); Mat COLOR_MIN(Scalar(15, 45, 45)); int main(int argc, char** argv){ Mat src,src2,hsv_img,mask,gray_img,initial_thresh,second_thresh,add_res,and_thresh,xor_thresh,result_thresh,rr_thresh,final_thresh; // Load source Image src = imread("banana2.jpg"); src2 = imread("Balanced_Image1.jpg"); imshow("Original Image", src); cvtColor(src,hsv_img,CV_BGR2HSV); imshow("HSV Image",hsv_img); //imwrite("HSV Image.jpg", hsv_img); inRange(hsv_img,COLOR_MIN,COLOR_MAX, mask); imshow("Mask Image",mask); cvtColor(src,gray_img,CV_BGR2GRAY); adaptiveThreshold(gray_img, initial_thresh, 255,ADAPTIVE_THRESH_GAUSSIAN_C, CV_THRESH_BINARY_INV,257,2); imshow("AdaptiveThresh Image", initial_thresh); add(mask,initial_thresh,add_res); erode(add_res, add_res, Mat(), Point(-1, -1), 1); dilate(add_res, add_res, Mat(), Point(-1, -1), 5); imshow("Bitwise Res",add_res); threshold(gray_img,second_thresh,150,255,CV_THRESH_BINARY_INV | CV_THRESH_OTSU); imshow("TreshImge", second_thresh); bitwise_and(add_res,second_thresh,and_thresh); imshow("andthresh",and_thresh); bitwise_xor(add_res, second_thresh, xor_thresh); imshow("xorthresh",xor_thresh); bitwise_or(and_thresh,xor_thresh,result_thresh); imshow("Result image", result_thresh); bitwise_and(add_res,result_thresh,final_thresh); imshow("Final Thresh",final_thresh); erode(final_thresh, final_thresh, Mat(), Point(-1,-1),6); bitwise_or(src,src,rr_thresh,final_thresh); imshow("Segmented Image", rr_thresh); imwrite("Segmented Image.jpg", rr_thresh); waitKey(0); return 1; }` </code></pre>