opencv - Leptonica OpenCV Java 将 Mat 转换为 Pix,反之亦然

标签 opencv leptonica

我使用以下 lept4jOpenCV Maven 依赖项:

<!-- Leptonica -->
<dependency>
    <groupId>net.sourceforge.lept4j</groupId>
    <artifactId>lept4j</artifactId>
    <version>1.9.0</version>
</dependency>

<!-- OpenCV -->
<dependency>
    <groupId>org.openpnp</groupId>
    <artifactId>opencv</artifactId>
    <version>3.2.0-1</version>
</dependency>

我想同时使用 OpenCV 和 Leptonica 函数。为此,我需要能够将 Mat 转换为 Pix,并将 Pix 转换为 Mat。

这是我目前拥有的:

public static Pix matToGrayscalePix(Mat mat) {

    if (mat == null) {
        throw new IllegalArgumentException("Recycled matrix");
    }

    final byte[] bytes = new byte[(int) mat.total()];
    mat.get(0, 0, bytes);

    ByteBuffer buff = ByteBuffer.wrap(bytes);
    return Leptonica1.pixReadMem(buff, new NativeSize(buff.capacity()));
}

public static Mat pixToGrayscaleMat(Pix pix) {

    if (pix == null) {
        throw new IllegalArgumentException("Recycled matrix");
    }

    PointerByReference pdata = new PointerByReference();
    NativeSizeByReference psize = new NativeSizeByReference();
    int format = net.sourceforge.lept4j.ILeptonica.IFF_TIFF;
    Leptonica1.pixWriteMem(pdata, psize, pix, format);
    byte[] b = pdata.getValue().getByteArray(0, psize.getValue().intValue());

    return new MatOfByte(b).reshape(0, pix.h);
}

但这些功能目前无法使用。我做错了什么?

最佳答案

尝试以下操作:

public static Pix convertMatToPix(Mat mat) {
    MatOfByte bytes = new MatOfByte();
    Imgcodecs.imencode(".tif", mat, bytes);
    ByteBuffer buff = ByteBuffer.wrap(bytes.toArray());
    return Leptonica1.pixReadMem(buff, new NativeSize(buff.capacity()));
}

public static Mat convertPixToMat(Pix pix) {
    PointerByReference pdata = new PointerByReference();
    NativeSizeByReference psize = new NativeSizeByReference();
    Leptonica1.pixWriteMem(pdata, psize, pix, ILeptonica.IFF_TIFF);
    byte[] b = pdata.getValue().getByteArray(0, psize.getValue().intValue());
    Leptonica1.lept_free(pdata.getValue());
    return Imgcodecs.imdecode(new MatOfByte(b), Imgcodecs.CV_LOAD_IMAGE_UNCHANGED);
}

关于opencv - Leptonica OpenCV Java 将 Mat 转换为 Pix,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48868503/

相关文章:

java - IllegalArgumentException : width and height must be > 0 - error when loading an image using Imgcodecs. 已读

c++ - XIMEA:openCV 2.4.9 无法找到 Ximea 相机,尽管它可以与其他程序一起正常工作

opencv - 如何从 OCR 图像中过滤纹理

c++ - QT中的Tesseract

c++ - CMake:使用外部项目安装的标题

windows - 未解析的外部符号 _png_init_io 在函数 _pixReadStreamPng 中引用

python - OpenCV - 使用 VideoWriter 不提供文件

opencv - 使用 opencv 时用于 accull 的编译器命令

python - 使用 OpenCV 和 Python 获取图像中颜色的百分比

opencv - Tesseract&Opencv程序镜像问题显示一些错误