java - OpenCV 图像描述符到 JSON

标签 java json opencv mat opencv-features2d

我想在服务器上存储一些图像描述符,以便在 Android 手机上进行图像匹配时,我可以获取预先计算的图像描述符,而不是即时执行。我已经成功创建了一个可以获取输入图像并输出最佳匹配的应用程序,但是我在将图像描述符矩阵放入 JSON 文件时遇到了一些问题。

下面我放置了一些代码,我试图调整这些代码以执行我想要的功能,但我遇到了这些行的错误:

mat.get(0, 0, data);

它给出的错误是:

Mat data type is not compatible: 5

描述符矩阵的类型为 CV_32FC1,但它将其视为 CV_8SC1。完整代码在下面,我的想法是将描述符矩阵传递给 matToJson,然后将输出存储在服务器上,然后使用 matFromJson 检索 JSON 文件的内容。我也无法解析 Base64.DEFAULT,因为它显示错误。任何帮助将不胜感激。

    public static String matToJson(Mat mat){        
    JsonObject obj = new JsonObject();

    if(mat.isContinuous()){
        int cols = mat.cols();
        int rows = mat.rows();
        int elemSize = (int) mat.elemSize();    

        byte[] data = new byte[cols * rows * elemSize];

        mat.get(0, 0, data);

        obj.addProperty("rows", mat.rows()); 
        obj.addProperty("cols", mat.cols()); 
        obj.addProperty("type", mat.type());

        // We cannot set binary data to a json object, so:
        // Encoding data byte array to Base64.
        String dataString = new String(Base64.encode(data, Base64.DEFAULT)); //Error here as well .default does not exist

        obj.addProperty("data", dataString);            

        Gson gson = new Gson();
        String json = gson.toJson(obj);

        return json;
    } else {
        System.out.println("Mat not continuous.");
    }
    return "{}";
}

public static Mat matFromJson(String json){
    JsonParser parser = new JsonParser();
    JsonObject JsonObject = parser.parse(json).getAsJsonObject();

    int rows = JsonObject.get("rows").getAsInt();
    int cols = JsonObject.get("cols").getAsInt();
    int type = JsonObject.get("type").getAsInt();

    String dataString = JsonObject.get("data").getAsString();       
    byte[] data = Base64.decode(dataString.getBytes(), Base64.DEFAULT); 

    Mat mat = new Mat(rows, cols, type);
    mat.put(0, 0, data);

    return mat;
}

最佳答案

找到问题的解决方案 here ,问题是由于在数组中使用了不正确的数据类型引起的。而不是使用字节,它应该是 float 的。但是我在上面链接的解决方案要好得多,因为它会在对数据进行编码之前检查数据类型。

关于java - OpenCV 图像描述符到 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35806067/

相关文章:

java - 如何使用当前日期作为函数输入获取月份名称

json - 无法运行react js项目

javascript - 在JavaScript中处理嵌套对象

javascript - 带有 JSON 数据源的 C3.js 流 api 不起作用

python - 如何将 cv2 处理后的图像保存到 Django 模型中?

java - 移动二维数组中的特定列

java - 由于安全规则,Firestore 上出现 "PERMISSION_DENIED"问题

java - Collections.synchronizedList 和同步

android - 如何在Android Studio 1.5中导入openCV 3.1

c++ - 如何使用 POCO 库将 C++ 对象传输到 Web 服务