INDArray image = loader.asMatrix(file);
How to convert INDArray to Json String and from Json String to INDArray. I searched in google it is not showing any results recording this.
INDArray image = loader.asMatrix(file);
How to convert INDArray to Json String and from Json String to INDArray. I searched in google it is not showing any results recording this.
Fiddling around I see that INDArray
has a data()
method (See INDArray API)
This gives you a DataBuffer
which in turn has methods to export it as a Java array (See DataBuffer API)
So I reckon you should these and do:
INDArray image = loader.asMatrix(file);
DataBuffer dataBuffer = image.data();
int[] array = dataBuffer.asInt(); // or any type you want
Now you have a Java array, you can use Gson
to make a Json String
Gson gson = new Gson();
String jsonString = gson.toJson(array);
I assume you can probably do the same in the other way (JSON to INDArray) Use Gson to transform your json string into java array then create an INDArray out of it. See user guide Creating NDArrays from Java arrays
INDArray matrix= imageLoader.asMatrix(file);
System.out.println("INDArray Original: " + matrix);
DataBuffer buff= matrix.data();
double[] array= buff.asDouble();
Gson gson= new Gson();
String imageStr= gson.toJson(array);
ArrayList<Double> result= gson.fromJson(imageStr, ArrayList.class);
double[] r= ArrayUtil.toArrayDouble(result);
int[] shape = matrix.shape();
INDArray final_array= Nd4j.create(r, shape, 'c');
System.out.println("After Java array to INDarray: " + final_array.toString());
Complete version of code to convert INDArray to Gson and from GSON to INDArray.
for 2d array:
INDArray matrix = YOUR_MATRIX;
double[][] java2dArray = matrix.toDoubleMatrix();
INDArray matrix = ND4j.create(java2dArray);