I have a requirement to produce graphs of matrices and display these graphs on a JSP. The project has been developed in Java and so far all my operations relating to matrices are being performed using the MatLabControl API
http://code.google.com/p/matlabcontrol/ .
I wanted to return the matrices produced by MATLAB (especially eigen value matrices and wavelets). MATLAB provides a function "im2java" that converts graph image from its MATLAB representation to a java.awt.Image. My code used to get the image data in MatlabControl was as follows:
public Image produceEigenValueGraph(final double [][] matrix) {
final double [][] maxEigenValueMatrix =
extractOutMaxEigenValues(matrix);
Image matlabPlotImage = null;
try {
MatlabNumericArray matLabEigenValueMatrix =
new MatlabNumericArray(maxEigenValueMatrix, null);
matLabTypeConverter.setNumericArray("eigen",
matLabEigenValueMatrix);
matLabProxy.setVariable("amountOfTime", matrix.length - 1);
matLabProxy.eval("time");
matLabProxy.eval("plot(time, eigen)");
matLabProxy.eval("frame=getframe");
final Object [] returnedMatlabArguements =
matLabProxy.returningEval("im2java(frame.cdata)", 1);
matlabPlotImage =
(Image)returnedMatlabArguements[0];
} catch (MatlabInvocationException mie) {
mie.printStackTrace();
}
return matlabPlotImage;
}
The code returns a nested exception:
Caused by: java.io.WriteAbortedException: writing aborted;
java.io.NotSerializableException: sun.awt.image.ToolkitImage
Which basically puts an end to any hope of the above code working, unless I am incorrect in my use.
N.B The code does produce a correct graph it fails to return it in java.awt.Image
My questions are:
-Is the above code the correct/only way to return images to a java program from Matlab?
-If it is what would be the best alternatives to using Matlab, Java API or otherwise?
Is this the line that causes the exception?
matlabPlotImage = (Image)returnedMatlabArguements[0];
In answer to your question
"-Is the above code the correct/only way to return images to a java program from Matlab?"
You can call java classes from Matlab so you could also use the java in a Matlab file and call that to replace
final Object [] returnedMatlabArguements = matLabProxy.returningEval("im2java(frame.cdata)", 1);
matlabPlotImage = (Image)returnedMatlabArguements[0];
The error is being thrown because Image is not serializeable. An option would be to save it as a file in some image format (jpg,png,tiff) using either matlab or java and return File instead of Image.
"-If it is what would be the best alternatives to using Matlab, Java API or otherwise?"
Mathworks provide a Java api to perform a number of linear algebra calculations that you could implement.
http://math.nist.gov/javanumerics/jama/#Package
Alternatively the Apache Commons Math project provide a wide range of linear algebraic functions as well as other tools. http://commons.apache.org/math/userguide/linear.html
I would check other posts for suggestions on graphing in java
constructing graphs in Java
Java Graphing Libraries for Web Applicattions?
Related
I am using MLeap to run a Pyspark logistic regression model in a java program. Once I run the pipeline I am able to get a DefaultLeapFrame object with one row Stream(Row(1.3,12,3.6,DenseTensor([D#538613b3,List(2)),1.0), ?).
But I am not sure how to actually inspect the DenseTensor object. When I use getTensor(3) on this row I get an object. I am not familiar with Scala but that seems to be how this is meant to be interacted with. In Java how can I get the values within this DenseVector?
Here is roughly what I am doing. I'm guessing using Object is not right for the type. . .
DefaultLeapFrame df = leapFrameSupport.select(frame2, Arrays.asList("feat1", "feat2", "feat3", "probability", "prediction"));
Tensor<Object> tensor = df.dataset().head().getTensor(3);
Thanks
So the MLeap documentation for the Java DSL is not so good but I was able to look over some unit tests (link) that pointed me to the right thing to use. In case anyone else is interested, this is what I did.
DefaultLeapFrame df = leapFrameSupport.select(frame, Arrays.asList("feat1", "feat2", "feat3", "probability", "prediction"));
TensorSupport tensorSupport = new TensorSupport();
List<Double> tensor_vals = tensorSupport.toArray(df.dataset().head().getTensor(3));
I have this code that works for python
X = numpy.loadtxt("compiledFeatures.csv", delimiter=",")
model = load_model("kerasnaive.h5")
predictions = model.predict(X)
print(predictions);
and I am trying to write a code with the same functionality in java,
I have written this code but it do not works, anyone knows what I am doing wrong or is there another simpler way to do it?
the code is going to the catch block, and during debugging the code it seems that all the information gained from the model file is null
path = String.format("%s\\kerasnaive.h5", System.getProperty("user.dir"),
pAgents[i]);
try {
network = KerasModelImport.importKerasModelAndWeights(path, false);
}
catch (Exception e){
System.out.println("cannot build keras layers");
}
INDArray input = Nd4j.create(1);
input.add(featuresInput); //an NDarray that i got in the method
INDArray output = network[i].outputSingle(input);
it seems that the model does not built (the network is still null)
the code for python loads the model and it works,
in java i get the error: "Could not determine number of outputs for layer: no output_dim or nb_filter field found. For more information, see http://deeplearning4j.org/model-import-keras."
although the same file is used in both casses
Thanks,
Ori
You are currently importing the trained keras model using importKerasModelAndWeights. I'm not sure how you trained your model, but in Keras there are two types of models available: the Sequential model, and the Model class that uses the functional API. You can read more here.
If you used the Sequential model when you created the network, you need to use the importKerasSequentialModel function. Keras Sequential models.
How to convert this C++ opencv code . (this code is from camshift tracking demo in opencv https://github.com/Itseez/opencv/blob/master/samples/cpp/camshiftdemo.cpp )
Mat roi(hue,selection), maskroi(mask,selection);
into javacv code?
The neweast javacpp presets javacpp-presets-0.9 already hava whole opencv javacv version implementation. Check if the functions you need is available.
https://github.com/bytedeco/javacpp-presets/tree/master/opencv
If not, I think you need to see the definition(implemetaion) of the two c++ function roi() and maskroi() to convert very line code into javacv counterpart by yourself.
And, google group of javacpp is also a best place to ask if you hava javacpp related questions. http://groups.google.com/group/javacpp-project
Note:
for c++ output parameter type(call by pointer or call by reference), you need to understand java function parameter has no output type, so you need to use array instead as workaround, for example:
C++ code:
void detectBothEars(Mat input, Rect* left, Rect* right);
The javacv counterpat should be:
void detectBothEarsRect(Mat input, Rect[] left, Rect[] right);
And the client code is:
Rect[] leftRect = new Rect[1];
Rect[] rightRect = new Rect[1];
detectBothEars(face, leftRect , rightRect);
The same constructor is available from Java: public Mat(Mat m, Rect roi)
So, we can basically do the same thing:
Mat roi = new Mat(hue, selection), maskroi = new Mat(mask, selection);
I need to call this MATLAB code from Java code. The code clusters an image according to the specified number of clusters and the specified initial cluster centers (i.e. [176;137] in this code).
nrows = size(a_image,1);
ncols = size(a_image,2);
double_a_2_image = double(reshape(a_image,nrows*ncols,1));
nColors = 2;
[cluster_idx_2_a cluster_center] =
kmeans(double_a_2_image,nColors,'distance','sqEuclidean','start',repmat([176;137],
[1,1,3]));
a_pixel_labels_2 = reshape(cluster_idx_2_a,nrows,ncols);
figure('Name','a* image labeled by cluster index: 2 colors'),imshow(a_pixel_labels_2,
[]);
What is the best tool to convert this code into jar file (or maybe .class file)? Another point: I need to run the resulted jar file on a machine that do not have matlab installed. Is that possible or should I install MATLAB Compiler Runtime (MCR) on this machine?
A simple search on google gives you this link : MATLAB Builder JA, which generate a Java wrapper around your MATLAB code. And for your second question, you won't need it, as the wrapper is taking care of the MATLAB code itself.
I need programmatically extract frames from mp4 video file, so each frame goes into a separate file. Please advise on a library that will allow to get result similar to the following VLC command (http://www.videolan.org/vlc/):
vlc v1.mp4 --video-filter=scene --vout=dummy --start-time=1 --stop-time=5 --scene-ratio=1 --scene-prefix=img- --scene-path=./images vlc://quit
Library for any of these Java / Python / Erlang / Haskell will do the job for me.
Consider using the following class by Popscan. The usage is as follows:
VideoSource vs = new VideoSource("file://c:\test.avi");
vs.initialize();
...
int frameIndex = 12345; // any frame
BufferedImage frame = vs.getFrame(frameIndex);
I would personally look for libraries that wrap ffmpeg/libavcodec (the understands-most-things library that many encoders and players use).
I've not really tried any yet so can't say anything about code quality and ease, but the five-line pyffmpeg example suggests it's an easy option - though it may well be *nix-only.