gpt4 book ai didi

java - 提取文本 OpenCV (Java)

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:40:33 25 4
gpt4 key购买 nike

我试图在图像中找到文本的边界框。我找到了一个 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的方法贴出结果)

使用 C++: cpp

使用 Java: java

最佳答案

以下是我在您的 Java 代码中看到的与 C++ 实现相比的两个主要差异。

  1. 你的形态内核是 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));
  1. 您没有将 maskROI 设置为零。

    Mat maskROI = new Mat(mask, rect);

在调用 drawContours 之前添加以下代码行。

maskROI.setTo(new Scalar(0, 0, 0));

关于java - 提取文本 OpenCV (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34271356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com