Does the Android OpenCV binary have data persistence functions?

后端 未结 2 405
走了就别回头了
走了就别回头了 2020-12-06 15:50

I\'d like to be able to persist matrices to disk. The c,c++ version of OpenCV supports with with the function cvWrite. I don\'t wee an equivalent function for the Android bi

2条回答
  •  萌比男神i
    2020-12-06 16:24

    Because OpenCV4Android does not yet have its own persistence, in my opinion the most universal way to store a Mat is to first convert it to a data-interchange format like JSON.

    After you are able to do that conversion you have a lot of flexibility to store it. JSON is easily converted to a String and/or sent through a network connection.

    With OpenCV C++ you are able to store data as YAML, but that is not available for Android yet like it was pointed by Andrey Kamaev. JSON here has the same purpose as YAML.

    To parse JSON in Java you can use this easy to use library Google GSON.

    And here is my first attempt to do exactly that (I did a simple test and it worked, let me know if there are problems):

    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));
    
            obj.addProperty("data", dataString);            
    
            Gson gson = new Gson();
            String json = gson.toJson(obj);
    
            return json;
        } else {
            Log.e(TAG, "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;
    }
    

提交回复
热议问题