2012-03-06 28 views

回答

0

由於OpenCV4Android還沒有自己的持久性,在我看來,存儲Mat的最普遍的方法是首先將它轉換爲像JSON這樣的數據交換格式。

當你能夠做這種轉換後,你有很大的靈活性來存儲它。 JSON很容易轉換爲字符串和/或通過網絡連接發送。

隨着OpenCV C++ you are able to store data as YAML,但這不適用於Android,但它是Andrey Kamaev指出的。這裏的JSON與YAML具有相同的用途。

要解析Java中的JSON,你可以使用這個易於使用的library Google GSON

這裏是我第一次做的正是嘗試(我做了一個簡單的測試,它的工作,讓我知道,如果有問題):

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