我试图在图像中找到文本的边界框。我找到了一个c ++实现here。
现在我尝试将其转换为这样的Java代码:
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import org.opencv.core.*;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.*;
public class Scritte {
public static void main(String[] args) {
// Load the native library.
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
new Nuova().analizza();
}
}
class Nuova{
public void analizza(){
Mat Main = Highgui.imread("/.../Ole.png");
Mat rgb = new Mat();
Imgproc.pyrDown(Main, rgb);
Mat small = new Mat();
Imgproc.cvtColor(rgb, small, Imgproc.COLOR_RGB2GRAY);
Mat grad = new Mat();
Mat morphKernel = Imgproc.getStructuringElement(Imgproc.MORPH_ELLIPSE, new Size(3,3));
Imgproc.morphologyEx(small, grad, Imgproc.MORPH_GRADIENT , morphKernel);
Mat bw = new Mat();
Imgproc.threshold(grad, bw, 0.0, 255.0, Imgproc.THRESH_BINARY | Imgproc.THRESH_OTSU);
Mat connected = new Mat();
morphKernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(1,9));
Imgproc.morphologyEx(bw, connected, Imgproc.MORPH_CLOSE , morphKernel);
Mat mask = Mat.zeros(bw.size(), CvType.CV_8UC1);
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Mat hierarchy = new Mat();
Imgproc.findContours(connected, contours, hierarchy, Imgproc.RETR_CCOMP, Imgproc.CHAIN_APPROX_SIMPLE, new Point(0, 0));
for(int idx = 0; idx < contours.size(); idx++)
{
Rect rect = Imgproc.boundingRect(contours.get(idx));
Mat maskROI = new Mat(mask, rect);
Imgproc.drawContours(mask, contours, idx, new Scalar(255, 255, 255), Core.FILLED);
double r = (double)Core.countNonZero(maskROI)/(rect.width*rect.height);
if (r > .45 && (rect.height > 8 && rect.width > 8))
{
Core.rectangle(rgb, rect.br() , new Point( rect.br().x-rect.width ,rect.br().y-rect.height), new Scalar(0, 255, 0));
}
String outputfile = "trovato.png";
Highgui.imwrite(outputfile,rgb);
}
}
}
我认为错误是在FOR循环中,但我无法解决它。 任何人都可以帮助我吗?
(下面我用C ++和Java中的方法发布结果)
答案 0 :(得分:3)
以下是我在Java代码中看到的与C ++实现相比的两个主要差异。
你的形态内核是9 x 1(h x w),而在原始代码中它是1 x 9.所以从
改变它morphKernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(1,9));
到
morphKernel = Imgproc.getStructuringElement(Imgproc.MORPH_RECT, new Size(9, 1));
您没有将maskROI设置为零。
Mat maskROI = new Mat(mask, rect);
在调用drawContours之前添加以下代码行。
maskROI.setTo(new Scalar(0, 0, 0));