我已应用全局阈值,自适应阈值,扩张和侵蚀,但无法获得预期结果。
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);
这是最终图片:
答案 0 :(得分:4)
根据您所需的结果,此代码可以改进。通过这种方法,您可以删除大多数小点。我希望它对你有所帮助。
#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);
}