【问题标题】:Leptonica OpenCV Java convert Mat to Pix and vise versaLeptonica OpenCV Java 将 Mat 转换为 Pix,反之亦然
【发布时间】:2018-02-19 14:41:22
【问题描述】:

我使用以下 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);
}

但是这些功能现在不起作用。我做错了什么?

【问题讨论】:

    标签: opencv leptonica


    【解决方案1】:

    尝试以下方法:

    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);
    }
    

    【讨论】:

      猜你喜欢
      • 2017-01-10
      • 2015-06-28
      • 2015-02-05
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-05
      相关资源
      最近更新 更多