1 | initial version |
public void removeBorder( String filePath ) { Mat grayImage = Imgcodecs.imread( filePath, Imgcodecs.IMREAD_GRAYSCALE ); Mat thresholdInverted = new Mat(); Imgproc.threshold( grayImage, thresholdInverted, 127.0, 255.0, Imgproc.THRESH_BINARY_INV + Imgproc.THRESH_OTSU ); Imgcodecs.imwrite( "C:\abc1.png", thresholdInverted );
List<MatOfPoint> horizontalContours = morphOpenAndFindContours( thresholdInverted, new Size( 5, 1 ));
List<MatOfPoint> verticalContours = morphOpenAndFindContours( thresholdInverted, new Size( 1, 10 ));
this.drawWhiteContours( verticalContours, grayImage );
this.drawWhiteContours( horizontalContours, grayImage );
Imgcodecs.imwrite( "C:\\result.jpg", grayImage );
}
private void drawWhiteContours( List<MatOfPoint> contours, Mat image )
{
for ( int i = 0; i < contours.size(); i++ ) {
Imgproc.drawContours( image, contours, i, new Scalar( 255 ), -1 );
}
}
private List<MatOfPoint> morphOpenAndFindContours( Mat img, Size kSize)
{
Mat kernel = Imgproc.getStructuringElement( Imgproc.MORPH_RECT, kSize );
Mat openedImage = new Mat();
Imgproc.morphologyEx( img, openedImage, Imgproc.MORPH_OPEN, kernel, new Point( -1, -1 ), 1 );
Mat dilateKernel = Imgproc.getStructuringElement( Imgproc.MORPH_RECT, new Size( 5, 5 ) );
Imgproc.dilate( openedImage, openedImage, dilateKernel );
List<MatOfPoint> contours = new ArrayList<>();
Imgproc.findContours( openedImage, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE );
return contours;
}
public void removeBorder( String filePath ) { Mat grayImage = Imgcodecs.imread( filePath, Imgcodecs.IMREAD_GRAYSCALE ); Mat thresholdInverted = new Mat(); Imgproc.threshold( grayImage, thresholdInverted, 127.0, 255.0, Imgproc.THRESH_BINARY_INV + Imgproc.THRESH_OTSU ); Imgcodecs.imwrite( "C:\abc1.png", thresholdInverted );
List<MatOfPoint> horizontalContours = morphOpenAndFindContours( thresholdInverted, new Size( 5, 1 ));
List<MatOfPoint> verticalContours = morphOpenAndFindContours( thresholdInverted, new Size( 1, 10 ));
this.drawWhiteContours( verticalContours, grayImage );
this.drawWhiteContours( horizontalContours, grayImage );
Imgcodecs.imwrite( "C:\\result.jpg", grayImage );
}
private void drawWhiteContours( List<MatOfPoint> contours, Mat image )
{
for ( int i = 0; i < contours.size(); i++ ) {
Imgproc.drawContours( image, contours, i, new Scalar( 255 ), -1 );
}
}
private List<MatOfPoint> morphOpenAndFindContours( Mat img, Size kSize)
{
Mat kernel = Imgproc.getStructuringElement( Imgproc.MORPH_RECT, kSize );
Mat openedImage = new Mat();
Imgproc.morphologyEx( img, openedImage, Imgproc.MORPH_OPEN, kernel, new Point( -1, -1 ), 1 );
Mat dilateKernel = Imgproc.getStructuringElement( Imgproc.MORPH_RECT, new Size( 5, 5 ) );
Imgproc.dilate( openedImage, openedImage, dilateKernel );
List<MatOfPoint> contours = new ArrayList<>();
Imgproc.findContours( openedImage, contours, new Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE );
return contours;
}