Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear the small black dots from image in OpenCV using Java?

Tags:

java

opencv

This is the original imageI have applied global threshold,adaptive threshold,dilation and erosion also but cant get the expected result.

Imgproc.threshold(source2, destination2, 147, 255,Imgproc.THRESH_BINARY ); 

Highgui.imwrite("threshold.jpg", destination2);


Imgproc.adaptiveThreshold(destination2, destination2, 255,
Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY, 11,2);
Highgui.imwrite("Adpthreshold.jpg", destination2);


Mat destination3 = new Mat(source.rows(),source.cols(),source.type());double erosion_size = 0;
int dilation_size = 1;

Mat element = Imgproc.getStructuringElement(Imgproc.MORPH_CROSS, new  Size(2*erosion_size + 1, 2*erosion_size+1));
Imgproc.erode(destination2, destination3, element);
Highgui.imwrite("erosion.jpg", destination3);


Mat element1 = Imgproc.getStructuringElement(Imgproc.MORPH_CROSS, new  Size(2*dilation_size + 1, 2*dilation_size+1));
Imgproc.dilate(destination3, destination3, element1);
Highgui.imwrite("dilation.jpg", destination3);

Here is the final image:

like image 651
kush Avatar asked Dec 04 '25 02:12

kush


1 Answers

this code is open to improvement according to your desired result.by this approach you can remove most of small dots. i hope it helps you.

#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <iostream>

using namespace cv;
using namespace std;

int main( int, char** argv )
{
    Mat src,src_gray;
    src = imread("4sE4p.jpg");
    if (src.empty())
    {
        cerr << "No image supplied ..." << endl;
        return -1;
    }
    cvtColor( src, src_gray, COLOR_BGR2GRAY );
    src_gray = src_gray >160;
    src_gray.copyTo(src);
    imshow( "src_gray", src_gray );
    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;

    cv::Mat kernel = cv::Mat::ones(2, 10, CV_8U);
    erode(src_gray,src_gray, kernel, Point(-1,-1),2);


    findContours( src_gray, contours, hierarchy, RETR_LIST, CHAIN_APPROX_SIMPLE, Point(0, 0) );
    for( size_t i = 0; i< contours.size(); i++ )
    {
        Rect R = boundingRect(Mat(contours[i]));
        if( R.width*R.height < 300 )
        {
            Mat roi(src_gray,R);

            if (countNonZero(roi) < R.width*R.height*0.9 )
            {
                rectangle(src,R,Scalar(0,0,255));
                Mat croi(src,R);
                croi.setTo(255); // this line is to clear small dots
            }
        }
    }
    imshow( "result", src );

    waitKey(0);
    return(0);
}
like image 143
sturkmen Avatar answered Dec 05 '25 14:12

sturkmen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!