How to feed boolean placeholder by means of TensorFlowInferenceInterface.java? - java

I'm trying to launch trained in Keras Tensorflow graph by means of Java Tensorflow API.
Aside from standard input image placeholder, this graph contains 'keras_learning_phase' placeholder that is needed to be fed with a boolean value.
The thing is, there is no method in TensorFlowInferenceInterface for boolean values - you can only feed it with float, double, int or byte values.
Obviously, when I try to pass int to this tensor by means of this code:
inferenceInterface.fillNodeInt("keras_learning_phase",
new int[]{1}, new int[]{0});
I get
tensorflow_inference_jni.cc:207 Error during inference: Internal:
Output 0 of type int32 does not match declared output type bool for
node _recv_keras_learning_phase_0 = _Recvclient_terminated=true,
recv_device="/job:localhost/replica:0/task:0/cpu:0",
send_device="/job:localhost/replica:0/task:0/cpu:0",
send_device_incarnation=4742451733276497694,
tensor_name="keras_learning_phase", tensor_type=DT_BOOL,
_device="/job:localhost/replica:0/task:0/cpu:0"
Is there a way to circumvent it?
Maybe it is possible somehow to explicitly convert Placeholder node in graph to Constant?
Or maybe it is possible to initially avoid creation of this Placeholder in the graph?

The TensorFlowInferenceInterface class essentially is a convenience wrapper over the full TensorFlow Java API, which does support boolean values.
You could perhaps add a method to TensorFlowInferenceInterface to do what you want. Similar to fillNodeInt, you could add the following (note the caveat that booleans in TensorFlow are represented as one byte):
public void fillNodeBool(String inputName, int[] dims, bool[] src) {
byte[] b = new byte[src.length];
for (int i = 0; i < src.length; ++i) {
b[i] = src[i] ? 1 : 0;
}
addFeed(inputName, Tensor.create(DatType.BOOL, mkDims(dims), ByteBuffer.wrap(b)));
}
Hope that helps. If it works, I'd encourage you to contribute back to the TensorFlow codebase.

This is in addition to the answer by ash, as the Tensorflow API has changed a little. Using this worked for me:
public void feed(String inputName, boolean[] src, long... dims) {
byte[] b = new byte[src.length];
for (int i = 0; i < src.length; i++) {
b[i] = src[i] ? (byte) 1 : (byte) 0;
}
addFeed(inputName, Tensor.create(Boolean.class, dims, ByteBuffer.wrap(b)));
}

Related

Tensorflow on Java: how to perform RGB to BGR operation?

I need to convert my 3-D tensor containing RGB image to BGR.
All the sources I've found on the web use python and they refer to operations that are either absent or different on java:
reverse does not accept an index but a boolean as second input
I've found the stack/unstack method, but unstack does not exist
Stack and Unstack operations are actually called as they have previously been on the other platforms, that is, Pack and Unpack. *
So, to perform the requested operation of transforming a Tensor representing an image in RGB to an image in BGR, the unstack/stack way can be followed.
public <T> Output<T> rgbToBgr(Output<T> input) {
return stackReverted(unstack(input));
}
// where g is Graph
public <T> Output<T>[] unstack(Output<T> input) {
return (Output<T>[]) g.opBuilder("Unpack", "Unpack")
.addInput(input)
.setAttr("axis", -1)
.setAttr("num", 3)
.build().outputList(0, 3);
}
public <T> Output<T> stackReverted(Output<T>[] input){
GraphOperationBuilder graphOperationBuilder = g.opBuilder("Pack", "Pack")
.setAttr("axis", -1);
Output<T>[] newInput = Arrays.copyOf(input, input.length);
for (int i = 0; i < input.length; i++)
newInput[i] = input[input.length - 1 - i];
graphOperationBuilder.addInputList(newInput);
return graphOperationBuilder.build().output(0);
}
There is no trace anywhere. If anybody can find documentation for Java, please post it.

eval function in C resulting in negative

I am using java 11, Eclipse IDE.
I am designing a program that needs some calculations, I am writing that program in java, so I was trying to find something similar to a function called "eval()", which evaluates an equation. So, I implemented that function in C and turned it into a ".dll" file and used it inside java.
My main problem is when I pass the equation into the eval function, and it returns a double which is negative and very huge, like : I passed it "1.0+0.5^2", and it resulted "-9.255963134931783E61", it is impossible to get to a result like that!
NOTE : it has always returned the right result, but at the last piece of execution, it has returned the above! Why? How? I am using the same eval function.
I will only show you the important parts and leave the rest, which is not important :
All codes :
eval.c :
int evaluate(char* line, double* val);
static int do_op(void);
static int do_paren(void);
static void push_op(char op);
static void push_arg(double arg);
static STATUS pop_arg(double* arg);
static STATUS pop_op(int* op);
static char* getexp(char* str);
static char* getop(char* str);
static char* getop(char* str);
JNIEXPORT jdouble JNICALL Java_application_Main_eval
(JNIEnv* env, jobject object, jstring str) {
const char* strs = env->GetStringUTFChars(str, false);
char* equation = const_cast<char*>(strs);
double result;
evaluate(equation, &result);
printf("the result is : %f", result);
jdouble* returnResult = new jdouble(result);
return *returnResult;
}
The native eval method in java :
static {
System.load(System.getProperty("user.dir")+"\\eval.dll");
}
public native double eval(String equation);
the java method that resulted something odd at the end :
String evaluateEquation(String e) {
// we will truncate the brackets into pieces and eval every piece,
// and then return it without brackets by replacing it inside the equation!
StringBuilder equation = new StringBuilder(e);
int count = countBrackets(equation);
int[] pos;
String part;
String result;
// TODO : fix here :
BigDecimal tempResult = new BigDecimal(0);
while (count!=0) { // every one loop, it will truncate, evaluate, replace the new value!
pos = lastBrackets(equation.toString());
part = equation.substring(pos[0], pos[1]+1);
System.out.println("evaluating this part : "+part);
tempResult = new BigDecimal(new Main().eval(part));
System.out.println(tempResult.toString());
result = truncateDecimals(tempResult);
equation.replace(pos[0], pos[1]+1, result);
System.out.println(equation.toString());
count--;
}
System.out.println(equation.substring(0, equation.length()));
part = equation.substring(0, equation.length()-1);
finalResult = new BigDecimal(new Main().eval(part));
System.out.println("FinalResult is : "+truncateDecimals(finalResult));
return truncateDecimals(finalResult);
}
If you have read the "eval.c" program, you will notice that it takes a "char*" and a "double&". I have taken care of these conversions and I think they have a relation with this bug. The method always returns the right result, except at one place, which is at the end of the "evaluateEquation" method.
Based on my knowledge, any number stored inside the computer memory gets to negative ONLY when we change it to a negative OR it extends on its maximum number to store. if the number breaks its limit, it will turn into a negative.
However, I noticed something, the number that is negative is being repeated again and again every time I call the eval function in the end of the "evaluateEquation" function I get the same result, which is : "-9.255963134931783E61".
If you have any assumptions, explanation or anything. Please, feel free to talk. I will never down-vote anyone who is trying to help me.
NOTE : this is the original C code that I used to make the dll file : http://stjarnhimlen.se/snippets/eval.c
The number -9.255963134931783E61 has the internal representation 0xCCCCCCCCCCCCCCCC, which strongly suggests that it is an uninitialised value.
Since you don't check the return value from evaluate, that suggests that it is returning an error condition, because in that case, evaluate does notset the value pointed to by its second argument.
I have noticed that the code is missing something. I revised it, and I remembered that a dll file is only loaded once when the program starts, so all the variables are being deleted or cleaned up. That caused the returned value to be odd and repeated continuously after the used arrays are full. So, I created a function to clear :
void clear() {
for (int i = 0; i!=256 ; i++) {
op_stack[i] = NULL;
arg_stack[i] = NULL;
token[i] = NULL;
}
op_sptr = 0;
arg_sptr = 0;
parens = 0;
state = 0;
}

How to convert c++ operator to Java

I'm trying to use the OpenCV library (Java version). I found some code written in C++and I'm trying to rewrite it to Java. However, I can't understand one construction.
Here is the C++ code:
void scaleDownImage(cv::Mat &originalImg,cv::Mat &scaledDownImage )
{
for(int x=0;x<16;x++)
{
for(int y=0;y<16 ;y++)
{
int yd =ceil((float)(y*originalImg.cols/16));
int xd = ceil((float)(x*originalImg.rows/16));
scaledDownImage.at<uchar>(x,y) = originalImg.at<uchar>(xd,yd);
}
}
}
I can't understand how to translate this line:
scaledDownImage.at<uchar>(x,y) = originalImg.at<uchar>(xd,yd);
have a look at the Mat accessor functions here: http://docs.opencv.org/java/org/opencv/core/Mat.html#get(int,%20int)
so, to translate your example:
scaledDownImage.at<uchar>(r,c) = originalImg.at<uchar>(rd,cd); // c++
would be :
byte [] pixel = new byte[1]; // byte[3] for rgb
originalImg.get( rd, cd, pixel );
scaledDownImage.put( r,c, pixel );
note, that it's (row,col), not (x,y) !
uchar = unsigned char.
This statement:
scaledDownImage.at<uchar>(x,y)
returns unsigned char(I guess, pointer) at positions(x,y).
So, in java it will be like:
unsigned char scaledDownImageChar = scaledDownImage.charAt(x, y);
scaledDownImageChar = originalImg.charAt(x, y);
This is not real code, just an example.
It is called template, search generics for java.
Basically, the "at" method´s code uses some type T
(don´t know if it is called T or something else)
which could be int, float, char, any class...
just something which is unspecified at the moment
And in this case, you´re calling the method with T being an uchar

Bifurcation and ridge ending point

Is there any way to find Bifurcation point and ridge ending point in a Image (hand, vein), by using a Java code only not Matlab etc.? Can I achieve this by ImageJ Library of Java?
A scientific description you find in Minutiae Extraction from Fingerprint Images.
Some algorithms are implemented in OpenCV see the segmentation section.
The OpenCV library can be linked to java using JNI.
There is an ImageJ plugin that could help you to do that:
AnalyzeSkeleton
(for the source see here )
You can extract branching points and endpoints with the help of its SkeletonResult class.
Many thanks to help me out I went through AnalyzeSkeleton and got the result in SekeletonResult Response by Using IJ. for this I have used IJ.run(imp, "Skeletonize", "");
// Initialize AnalyzeSkeleton_
AnalyzeSkeleton_ skel = new AnalyzeSkeleton_();
skel.calculateShortestPath = true;
skel.setup("", imp);
// Perform analysis in silent mode
// (work on a copy of the ImagePlus if you don't want it displayed)
// run(int pruneIndex, boolean pruneEnds, boolean shortPath, ImagePlus origIP, boolean silent, boolean verbose)
SkeletonResult skelResult = skel.run(AnalyzeSkeleton_.NONE, false, true, null, true, false);
// Read the results
Object shortestPaths[] = skelResult.getShortestPathList().toArray();
double branchLengths[] = skelResult.getAverageBranchLength();
int branchNumbers[] = skelResult.getBranches();
long totalLength = 0;
for (int i = 0; i < branchNumbers.length; i++) {
totalLength += branchNumbers[i] * branchLengths[i];
}
double cumulativeLengthOfShortestPaths = 0;
for (int i = 0; i < shortestPaths.length; i++) {
cumulativeLengthOfShortestPaths +=(Double)shortestPaths[i];
}
System.out.println("totalLength "+totalLength);
System.out.println("cumulativeLengthOfShortestPaths "+cumulativeLengthOfShortestPaths);
System.out.println("getNumOfTrees "+skelResult.getNumOfTrees());
System.out.println("getAverageBranchLength "+skelResult.getAverageBranchLength().length);
System.out.println("getBranches "+skelResult.getBranches().length);
System.out.println("getEndPoints "+skelResult.getEndPoints().length);
System.out.println("getGraph "+skelResult.getGraph().length);
System.out.println("getJunctions "+skelResult.getJunctions().length);
System.out.println("getJunctionVoxels "+skelResult.getJunctionVoxels().length);
System.out.println("getListOfEndPoints "+skelResult.getListOfEndPoints().size());
System.out.println("getListOfJunctionVoxels "+skelResult.getListOfJunctionVoxels().size());
System.out.println("getMaximumBranchLength "+skelResult.getMaximumBranchLength().length);
System.out.println("getNumberOfVoxels "+skelResult.getNumberOfVoxels().length);
System.out.println("getQuadruples "+skelResult.getQuadruples().length); this method .but I am not able to find which method in Skeleton Result class returns bifuraction point could you please help me little more thanks Amar

How to pass byte arrays between Java and JavaScript

I need to access SecureRandom Java Object from Javascript. My ultimate goal is to grab 4 bytes from PRNG and convert it to Javascript integer variable. According to http://download.oracle.com/javase/1.4.2/docs/api/java/security/SecureRandom.html, the following two lines of Java code are supposed to do grab 4 random bytes:
byte bytes[] = new byte[4];
random.nextBytes(bytes);
My problems is that I don't know how to
1) allocate byte array suitable for passing to Java method
2) parse that array into integer afterwards
So far I have managed to getSeed() method which returns an array of random bytes. When I render HTML code provided below in Firefox it shows "[B#16f70a4", which appears to be a pointer or something.
<script>
var sprng = new java.security.SecureRandom();
random = sprng.getSeed(4);
document.write(random + "<br/>\n");
</script>
This makes me think that I succeed to instantiate and access Java class, but have a problem with type conversion.
Can anyone please help me to write allocateJavaByteArray(N) and convertJavaByteArrayToInt(N) to let the following code work:
var sprng = new java.security.SecureRandom();
var nextBytes = allocateJavaByteArray(4);
srng.nextBytes(nextBytes);
var nextInt = convertJavaByteArrayToInt(4);
Thank you in advance.
You could implement convertJavaByteArrayToInt like this:
function convertJavaByteArrayToInt(bytes) {
var r = 0;
for (var i = 0; i < bytes.length; i++) {
r += (bytes[i] & 0xff) << (8 * i);
}
return r;
}
allocateJavaByteArray is difficult to implement, because we cannot get the Class of byte. So it's not possible to use java.lang.reflect.Array.newInstance to create a byte[] instance. But here is a tricky implementation:
function allocateJavaByteArray(n) {
var r = "";
for (var i = 0; i < n; i++) {
r += "0";
}
return new java.lang.String(r).getBytes();
}
updated: It seems that above code not worked in FireFox 3.6. Here is another allocateJavaByteArray implementation, have a try:
function allocateJavaByteArray(n) {
var r = new java.io.ByteArrayOutputStream(4);
for (var i = 0; i < n; i++) {
r.write(0);
}
return r.toByteArray();
}
Normally you'd generate the random number on the server and pass it in the Request to the jsp.
You could simply generate a random integer in the first place, like this:
var nextInt = sprng.nextInt();
Java string is the only thing that will pass Java->JS or JS->Java without headache.
byte[] or any arry will be seen in JS as JSObject.
var sprng = new java.security.SecureRandom();
is
var foo= new java.package.SomeClass();
does work in Netscape/Mozilla/FF
It needs access to classes, so any java standard class or you need to load a jar and then access the class.
to orginal question:
create applet whith utility method:
public String someStringEncodedValue(){
return 1+"|"+2;
}
include applet into the page with unique id
JS find applet using unique id
call method
parse string ( split by | )

Categories