如下图所示的文本边框对 OCR 来说是一个非常糟糕的结果。
所以我使用 javaCV(OpenCV 的 java wrapper)来删除图像中文本周围的边框和框。结果相当令人满意。但我现在面临的问题是,它正在删除文本的水平和垂直行,就像下面的例子一样。
被移除的水平线以不同的颜色重新绘制。
我正在按照以下步骤删除边框
- 找到指定轮廓高度和宽度的水平和垂直轮廓。
- 用白色填充轮廓。
我在下面附上了我的代码片段。
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( "E:/threholded.jpg", 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( "E:/result.jpg", grayImage );
}
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;
}
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 );
}
}
那么如何只删除边框而不影响文本呢?Java中的解决方案更可取,但我对python没问题。