java opencv Features2d.drawMatches - Assertion failure or NullPointerException - java

I'm trying to create an image depicting matches between keypoints in images generated from sift files, using the Features2d.drawMatches method from openCV java API. I can't seem to figure out what kind of argument the method will take as an output parameter - I keep getting the following Assertion Error:
OpenCV(3.4.1) Error: Assertion failed (!outImage.empty()) in
cv::drawKeypoints, file C:\build\master_winpack-bindings-win32-vc14-
static\opencv\modules\features2d\src\draw.cpp, line 115
Exception in thread "main" CvException [org.opencv.core.CvException:
cv::Exception: OpenCV(3.4.1) C:\build\master_winpack-bindings-win32-vc14-
static\opencv\modules\features2d\src\draw.cpp:115: error: (-215)
!outImage.empty() in function cv::drawKeypoints
]
at org.opencv.features2d.Features2d.drawMatches_1(Native Method)
at org.opencv.features2d.Features2d.drawMatches(Features2d.java:71)
at com.company.GUI.ImagesView.matchPoints(ImagesView.java:94)
at com.company.GUI.ImagesView.<init>(ImagesView.java:69)
at com.company.Main.main(Main.java:17)
My code:
private void matchPoints() {
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
MatOfKeyPoint matKey1 = new MatOfKeyPoint(keyPoints1);
MatOfKeyPoint matKey2 = new MatOfKeyPoint(keyPoints2);
MatOfDMatch matDMatch = new MatOfDMatch(matches);
Mat output = new Mat();
//output = new Mat(matKey1.rows(), matKey1.cols(), CvType.CV_8U, Scalar.all(0));
if (!output.empty())
System.out.println("not empty");
else
System.out.println("empty");
Features2d.drawMatches(mat1, matKey1, mat2, matKey2, matDMatch, output);
HighGui.imshow("Matches", output);
}
The exact same assertion error shows up whether or not I un-comment the commented line, despite the empty() check below returning different values for these two Mats. I'm at loss, help would be much appreciated.

I can't comment, so I must write an answer:
I had the same problem and somehow solved it. It is no dependency error - I have solved it without changing my dependencies (or imported libraries).
If the matches computed correctly, there won't occure this specific error when calling this function.
In my code, the error was the call of the compute function. I tried to call this function with an FastFeatureDetector - but I somewhere have read that this detector can't find any matches.
Try to compute the
ORB extractor = ORB.create();extractor.compute(currentFrame, keyPoints, imgDescriptor);
When trying to compute the imgDescriptor, no error should occur; after matching you should be able to draw the matches.
Hope, I helped you or anyone else struggling with this kinda error.

Related

Rascal: Undeclared Annotation in std:///lang/java/flow/JavaToObjectFlow.rsc

In the following code snippet, I attempted to use the createOFG from JavaToObjectFlow.rsc:
void run(loc source) {
m = createM3FromEclipseProject(source);
set[Declaration] asts = createAstsFromEclipseProject(source, true);
FlowProgram p = createOFG(asts);
}
Upon executing this method, the following error was received:
|std:///lang/java/flow/JavaToObjectFlow.rsc|(4167,1,<153,26>,<153,27>):
Undeclared annotation: decl on Expression
Advice: |http://tutor.rascal-
mpl.org/Errors/Static/UndeclaredAnnotation/UndeclaredAnnotation.html|
Since the error is coming from std:///lang/java/flow/JavaToObjectFlow.rsc and none of our fellow students receive the same error, I am wondering what is going wrong. The error occurs in both the stable and unstable versions of Rascal.
you should be on unstable, as this message points to a known problem on stable.
are you sure you get exactly the same message on unstable? in that case, please tell me what you see on that line (153 of file /lang/java/flow/JavaToObjectFlow.rsc)
If you don't have a source location to click on to get you there, you can always browse the code from any rascal project:

getting a NULL pointer exception when trying to use Spark IDF.fit()

trying to run this example in Spark documentation. Getting the error below. Get the same error using the Java version of the example as well. The exact line where I get the error is:
idfModel = idf.fit(featurizedData)
Py4JJavaError: An error occurred while calling o1142.fit.
: org.apache.spark.SparkException: Job aborted due to stage failure: Task 7 in stage 256.0 failed 1 times, most recent failure: Lost task 7.0 in stage 256.0 (TID 3308, localhost): java.lang.NullPointerException
The data i'm using is obtained by reading a Json file which has few thousand records. In Java i'm reading the file as follows:
DataFrame myData = sqlContext.read().json("myJsonFile.json");
the rest of the code is exactly the same as in the example linked above. featurizedData is a valid DataFrame, I printed it's schema and the first element and everything looks as expected. I have no idea why I'm getting a null pointer exception.
The problem is you have nan as the text field for some columns.
Since the question is tagged with PySpark, use
data_nan_imputed = data.fillna("unknown", subset=["text_col1", .., "text_coln"])
This is a good practice if you have a number of text_cols that you want to combine them to make a single text_col. Otherwise, you can also use
data_nan_dropped = data.dropna()
to get rid of the nan columns and then fit this dataset. Hopefully, it will work.
For scala or java use similar nan filling statements.

How to give a default value to a List in Scala?

I have the following part of code which gives me java.lang.NullPointerException, I found the source and I know that I declared a variable but set it initially null and later in the program initialized it but I don't know how to give a default value without getting error! The List accepts two different types, Float and RDD.
Here is the part of the code that has problem in it:
case class RPN (sc:SparkContext, vp: VolumeProperty, var stack:List[Either[RDD[(Int, Array[Float])],Float]]) {
def this(s:SparkContext,v:VolumeProperty) = this(s,v,null); //Think here is the problem
def operand(x: Either[RDD[(Int, Array[Float])],Float]) = new RPN(sc,vp,stack = x :: stack) //gives error on this line
and I am getting following error:
Exception in thread "main" java.lang.NullPointerException
How can I solve it!
Use Nil instead of null. Nil is an empty list.

OpenCV 3.0.0 FaceDetect Sample fails

I am trying to get OpenCV running i am using the following
sample code
I get the following Error line displayed:
OpenCV Error: Assertion failed (!empty()) in cv::CascadeClassifier::detectMultiScale, file ..\..\..\..\opencv\modules\objdetect\src\cascadedetect.cpp, line 1580
Exception in thread "main" CvException [org.opencv.core.CvException: cv::Exception: ..\..\..\..\opencv\modules\objdetect\src\cascadedetect.cpp:1580: error: (-215) !empty() in function cv::CascadeClassifier::detectMultiScale
]
at org.opencv.objdetect.CascadeClassifier.detectMultiScale_1(Native Method)
at org.opencv.objdetect.CascadeClassifier.detectMultiScale(CascadeClassifier.java:176)
at org.maxbit.opencv.samples.DetectFaceDemo.run(SampleB.java:29)
at org.maxbit.opencv.samples.SampleB.main(SampleB.java:51)
Can any body tell me what that error means or how to debug this?
I also faced the problem. The problem is in the .getPath() return an absolute path of the format.
Eg: "/C:/Users/projects/FaceDetection/bin/com/face/detection/haarcascade_frontalface_alt.xml".
So change the code like this.
CascadeClassifier faceDecetor = new CascadeClassifier(FaceDetection.class.getResource("haarcascade_frontalface_alt.xml").getPath().substring(1));
This happens usually for two reasons.
Cascade classifier file lbpcascade_frontalface.xml not present at specified path.
Cascade classifier file is corrupted.
To get an error message instead of exception during runtime, try code sample as below. The CascadeClassifier constructor is silent, if it cannot load the cascade classifier XML. The onus is on the developer to call the empty() method and check if classifier is loaded correctly
CascadeClassifier cascade = new CascadeClassifier( CASCADE_CLASSIFIER_PATH );
if ( cascade.empty() ) {
//handler error here
}
Exception you got is from OpenCV native code assertion here.
I ran into this same error running on a Windows box. This sample runs on linux but not Windows.
The problem is in the .getPath() call after getResource() for both the xml file and the image.
The problem is that the URL.getPath() and the URL.getFile() both return an absolute path of the format "/c:/...".
The OpenCV routines choke on this it must be "c:/..." (no leading '/'). This seems like a bug in the early part of version 3.0.0?
I hope this helps, OpenCV for Java seems like a great tool ... but it is a bit frustrating when the examples don't work.
There is a problem with the latest openCV it doesn't work when you have spaces in your path so do this:
String s =CameraPanel.class.getResource("lbpcascade_frontalface.xml").getPath().substring(1);
String[] split = s.split("%20");
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < split.length-1; i++) {
stringBuilder.append(split[i]+" ");
}
stringBuilder.append(split[split.length-1]);
faceDetector = new CascadeClassifier(stringBuilder.toString());
I ran into the same issue: On windows, OpenCV chokes on both the prepended '\' and any whitespace in the path, as both Imad and Aung have noted. My solution is a bit shorter than Imad's:
Change this:
CascadeClassifier faceDecetor = new CascadeClassifier(
getClass().class.getResource("haarcascade_frontalface_alt.xml").getPath());
To this:
CascadeClassifier faceDecetor = new CascadeClassifier(
getClass().class.getResource("haarcascade_frontalface_alt.xml").getPath().substring(1).replaceAll("%20", " "));
For me the simplest solution was:
private void checkboxSelection(String classifierPath) {
// load the classifier(s)
faceCascade.load(classifierPath);
// Did it work?
if (faceCascade.empty()) {
// Try the full path
String resource = getClass().getResource(classifierPath).getPath();
// Discard leading / if present.
if ( resource.startsWith("/")) {
resource = resource.substring(1);
}
faceCascade.load(resource);
}
// now the video capture can start
cameraButton.setDisable(false);
}
I am using openCv 3.4.1
I think there's a bug in CascadeClassifier initializer.
In order to get rid of this error, I must call "load" once again. Hope this solution could help.
cascadeClassifier = new CascadeClassifier(mCascadeFile.getAbsolutePath());
cascadeClassifier.load(mCascadeFile.getAbsolutePath());
I faced problem on Mac (OSX) Java.
CameraFrame.class.getResource("haarcascade_frontalface_alt.xml").getPath().substring(1)
returned "Users/username/Desktop/JavaProjects/Camera/bin/haarcascade_frontalface_alt.xml".
whereas path should start with "/" therefore I appended "/".
face = new CascadeClassifier("/" +
CameraFrame.class.getResource("haarcascade_frontalface_alt.xml").getPath().substring(1));
It works OK now :)
I faced the same problem as well. It is just because the path you gave for 'haarcascade_frontalface_alt2.xml' might be incorrect of not proper. just copy the full path from file explorer and paste it. This solution works for me.
face_cascade = cv2.CascadeClassifier('C:/Users/xyz/FaceDetect/faceId/OpenCV-Python-Series-master/src/cascades/data/haarcascade_frontalface_alt2.xml')

CConvertException in Play! Framework

I'm fixing up a HTML template for rendering a PDF file. The problem is that the new code I'm using works for one template but throws a CConvertException in another. The console doesn't give me any hints other than the following error:
Oops: CConvertException
An unexpected error occured caused by exception CConvertException:
ERROR: An unhandled exception occured: ERROR: An Exception occured while reconstructing the pdf document: ERROR: An unhandled exception occured: null
The new code involves using a new Java Extension that converts a String into another, as follows:
#{if person?.name != null} ${person?.name.getInitials().toString()} #{/if}
For some reason, this exact code breaks one template but works just fine in another. What am I doing wrong?
Don't know for sure if this is the cause, but your use of the safe navigation operator ?. is kind of weird here. And wouldn't getInitials() automatically return a String?
Why not just write (without the surrounding if statement):
// Returns the name or an empty String if name or person is null.
${person?.name?.getInitials() ?: ""}

Categories