Error trying to detect faces in an image with OpenCV JAVA - java

I have used the code from this tutorial: http://opencvlover.blogspot.co.uk/2012/11/face-detection-in-javacv-using-haar.html
It has been slightly modified to read a different image, and display this image before attempting face detection (line 14). Through this I can confirm that the image is being loaded correctly.
The error occurs later at line 23. Here is the complete error code:
OpenCV Error: Null pointer (Invalid classifier cascade) in cvHaarDetectObjectsForROC,file ..\..\..\..\opencv\modules\objdetect\src\haar.cpp, line 1514
Exception in thread "main" java.lang.RuntimeException: ..\..\..\..\opencv\modules\objdetect\src\haar.cpp:1514: error: (-27) Invalid classifier cascade in function cvHaarDetectObjectsForROC
at com.googlecode.javacv.cpp.opencv_objdetect.cvHaarDetectObjects(Native Method)
at com.googlecode.javacv.cpp.opencv_objdetect.cvHaarDetectObjects(opencv_objdetect.java:238)
at FaceDetection.detect(FaceDetection.java:23)
at FaceDetection.main(FaceDetection.java:15)
Here is my complete program:
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import static com.googlecode.javacv.cpp.opencv_core.*;
import static com.googlecode.javacv.cpp.opencv_highgui.*;
import static com.googlecode.javacv.cpp.opencv_objdetect.*;
public class FaceDetection{
public static final String XML_FILE =
"resources/haarcascade_frontalface_default.xml";
public static void main(String[] args){
IplImage img = cvLoadImage("pic.jpg");
cvShowImage("",img);cvWaitKey(0);
detect(img);
}
public static void detect(IplImage src){
CvHaarClassifierCascade cascade = new
CvHaarClassifierCascade(cvLoad(XML_FILE));
CvMemStorage storage = CvMemStorage.create();
CvSeq sign = cvHaarDetectObjects(
src,
cascade,
storage,
1.5,
3,
CV_HAAR_DO_CANNY_PRUNING);
cvClearMemStorage(storage);
int total_Faces = sign.total();
for(int i = 0; i < total_Faces; i++){
CvRect r = new CvRect(cvGetSeqElem(sign, i));
cvRectangle (
src,
cvPoint(r.x(), r.y()),
cvPoint(r.width() + r.x(), r.height() + r.y()),
CvScalar.RED,
2,
CV_AA,
0);
}
cvShowImage("Result", src);
cvWaitKey(0);
}
}
Anybody know what is causing this error, or how it can be fixed? Thanks!

Solved!
I googled the "haarcascade_frontalface_default.xml", downloaded it and stuck it in my folder in the workspace, took /resources/ off of the filename in the XML string and it works.

Congrats on solving it. However to progress and learn, you must understand what went wrong.
The error occurred because the program cannot find the cascade classifier. I thought you declared the location of the classifier wrongly, but turns out you didn't have the classifier in the first place. You solved that by downloading a sample classifier and using it.
You do not necessarily have to put the classifier in the folder containing the program. You can also put it somewhere else and state the path of where the classifier is located.
I would also recommend you to train your own haar-classifier if you are really into object detection. This will help you understand better how cascade classifier works.

Related

Custom renameParticpant dialogue with "FATALERROR: No input element provided"

I am creating a custom renameParticpant to rename an Eclipse project's launch configuration files, and to change the APPNAME variable in the Makefile. The Makefile side works 100% of the time, but attempting to rename the launch configs causes the following error to occur:
<FATALERROR
FATALERROR: No input element provided
Context: <Unspecified context>
code: none
Data: null
>
This error occurs when the changes are being validated at the following line in org.eclipse.ltk.core.refactoring.PerformChangeOperation [line: 248].
fValidationStatus= fChange.isValid(new SubProgressMonitor(monitor, 1));
Below is a screenshot of the variable view. I suspect that my compositeChange is not in the correct format or is missing some information, however; the error dialogue and logs don't give any helpful information.
Debugger variable view of fChanges
The following is relevant code snippets:
// This one sparks joy (it works great, 100% success)
final HashMap<IFile, TextFileChange> textChanges = new HashMap<IFile, TextFileChange>();
// Stuff gets put inside
textChanges.put(makefile, changeAppname);
// This one does not spark joy (it runs, but results in an invalid Change)
final HashMap<IFile, RenameResourceChange> renameChanges = new HashMap<IFile, RenameResourceChange>();
// Stuff gets put inside
RenameResourceChange renameChange = new RenameResourceChange(
launch.getFile().getProjectRelativePath(), newLaunchName);
renameChanges.put(launch.getFile(), renameChange);
// This is where they get added to the hashmap.
CompositeChange result;
if (textChanges.isEmpty() && renameChanges.isEmpty()) {
result = null;
} else {
result = new CompositeChange(
String.format("Rename project references and dependencies for %1$s", proj.getName()));
for (Iterator<TextFileChange> iter = textChanges.values().iterator(); iter.hasNext();) {
result.add(iter.next());
}
for (Iterator<RenameResourceChange> iter = renameChanges.values().iterator(); iter.hasNext();) {
result.add(iter.next());
}
}
return result;
I looked into adding or generating a changeDescriptor, however that seems like the wrong approach.

Java+jopendocument: NullPointerException when using getCellAt(0,0)

In a Libreoffice Spreadsheet's sheet, I can get access to a Cell, but not to its value. I don't find my error, any feedback is welcome. Here is the code:
import java.io.File;
import java.io.IOException;
import org.jopendocument.dom.spreadsheet.MutableCell;
import org.jopendocument.dom.spreadsheet.Sheet;
import org.jopendocument.dom.spreadsheet.SpreadSheet;
public class MyClass {
protected Sheet dataSheet;
protected File dataCalcFile;
public static void main(String[] args) {
MyClass myClassInstance = new MyClass();
myClassInstance.loadData();
}
public void loadData() {
int numRows=0, numColumnas=0;
MutableCell cell=null;
try {
dataCalcFile = new File(""C:\\temp\\Data.ods"");
dataSheet = SpreadSheet.createFromFile(dataCalcFile).getSheet(0);
numRows = dataSheet.getRowCount();
System.out.println("Number of rows: " + numRows);
System.out.println("Cell at 0,0: " + dataSheet.getCellAt(0, 0));
System.out.println("Nullpointer Exception when getting cell value at 0,0: " + dataSheet.getValueAt(0, 0)); // *** THE INFAMOUS ONE ***
} catch (Exception e) {
System.out.println(e);
}
}
}
And here is the output at console:
Number of rows: 107
Cell at 0,0: <table:table-cell xmlns:table="urn:oasis:names:tc:opendocument:xmlns:table:1.0" table:style-name="ce1" xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" office:value-type="string" xmlns:calcext="urn:org:documentfoundation:names:experimental:calc:xmlns:calcext:1.0" calcext:value-type="string"><text:p xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">Carpeta</text:p></table:table-cell>
java.lang.NullPointerException
Just found that:
"Yes, LO 7 switched to OpenDocument 1.3. We're working on supporting it. In the mean time, you can change the format to "1.2 extended". Go to Options, then Load/Save, then General, then ODF format version."
It works for me, but am excited to hear my customers opinion...
I found that it must be some incompatibility between the library jopendocument and the newer versions of Libreoffice (7.x), as the code above:
Works as expected if the spreadsheet is edited with Libreoffice 6.4.3.2
Spits the null pointer exception out if the spreadsheet is edited with Libreoffice 7.0.1.2
In some version in between Calc produces an XML not understood by jopendocument.
Instead of using
getValueAt(0, 0),
you can use
getCellAt(0, 0).getElement().getValue()
It works for me.

Assertion failure in NSEvent?

thanks for taking the time to read this. I'm fairly new to JavaFX and have a weird error in my compiler that I would like some insight on.
Here's the error:
2018-09-13 19:09:36.387 java[8040:660455] unrecognized type is 4294967295
2018-09-13 19:09:36.387 java[8040:660455] *** Assertion failure in -[NSEvent _initWithCGEvent:eventRef:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/AppKit/AppKit-1652/AppKit.subproj/NSEvent.m:1969
Here is the code I am working with:
This is in a .java file named applicationSettings
public static double lookupUser(String name, String password) throws IOException {
InputStream inputStream = applicationSettings.class.getResourceAsStream("/files/users.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
XSSFSheet sheet = workbook.getSheetAt(0);
Integer lastRow = sheet.getPhysicalNumberOfRows();
int currentRow = 1;
while(currentRow < lastRow) {
if(sheet.getRow(currentRow).getCell(0).getStringCellValue().toLowerCase().equals(name.toLowerCase())) {
if(sheet.getRow(currentRow).getCell(1).getStringCellValue().toLowerCase().equals(password.toLowerCase())) {
double accessLevel = sheet.getRow(currentRow).getCell(2).getNumericCellValue();
System.out.println(accessLevel);
return accessLevel;
}
}
currentRow++;
}
return 4.0;
}
}
This is in a .java file named loginScreen
EventHandler<ActionEvent> loginClicked = new EventHandler<ActionEvent>() {
public void handle(ActionEvent event) {
double userFound = 0.0;
try {
userFound = applicationSettings.lookupUser(usernameField.getText(), passwordField.getText());
} catch (IOException e) {
e.printStackTrace();
}//END of Try/Catch
if(userFound == 1.0) { //1 is Admin Access
//TODO: Implement Login
System.out.println("Admin Login");
errorLabel.setVisible(false);
}else if(userFound == 2.0){ //2 is Elevated Access
//TODO: Elevated Access
System.out.println("Elevated Login");
errorLabel.setVisible(false);
}else if(userFound == 3.0){
//TODO: Basic Access
System.out.println("Basic Login");
errorLabel.setVisible(false);
}else{//Show Error
errorLabel.setVisible(true);
//TODO: Show Error
}//End If Statement
}
};
My Excel File is basically structured like this:
NAME PASSWORD ACCESS LEVEL
So for my login it would be like:
Trey Carey March3199; 1
This isn't going anywhere besides by church where it's not really doing anything besides automating some tedious tasks, so security isn't an issue.
Also, if there's anyway I can clean up some of these if statements and my code in general I would appreciate any tips or help!
Edit 2 13.11.2018:
This bug has been officially fixed now in JavaFX 12, was backported to JDK8 and approved to be backported to JFX 11. You can have a look at the bug report to find more information about it.JDK-8211304 Here is a link to the changes they've made. openjfx I'm personally not sure about the current license situation of JDK8 so I would advise to switch to the newest OpenJDK and OpenJFX if possible.
Hey there I'm experiencing the same issue you have and I can constantly reproduce it. The issue appears for me on JavaFX on macOS 10.14. You can simply create an application with a button that opens a second stage. If you invoke stage.showAndWait() (could be related to anything that holds the thread) on the second stage and then switch focus between different applications (I just alt-tab between my JavaFX app and Safari), the JavaFX Application crashes. Also reproducible in any IDE.
I actually found a bug report on the OpenJDK/OpenJFX bug tracker but there isn't much going on at the moment. JDK-8211137 Mac: JVM Crash due to uncaught exception
I don't have a solution yet as I'm having troubles pinning down the exact problem but I found a workaround that works in my specific case.
Edit:
If I'm using "stage.show()" I'm only getting the error but when using stage.showAndWait() or anything that does some kind of waiting loop, the application completely crashes.

How to resolve "Error: long vectors not supported yet: qap_encode.c:36"?

I am trying to connect java with R using Rserve
Java: 1.8.0_151
R: 3.5.0
OS: Mac 10.13.4 HighSierra
To connect R with Java, I typed the following on RStudio
install.packages("Rserve")
library(Rserve)
Rserve(args="--no-save")
things went smooth and I was so happy about it.
Then I jumped back to Java (Java Eclipse so to speak) and continued typing. Here is what I've done on Eclipse
package rserve;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.REngineException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
public class WordCloud1 {
public static void main(String[] args) throws REngineException,
REXPMismatchException {
RConnection c = new RConnection();
String path = "/Users/JinhoShin/Desktop/study/R/r_temp2";
String file = "seoul_new.txt";
c.parseAndEval("library(KoNLP)");
c.parseAndEval("useSejongDic()");
c.parseAndEval("library(wordcloud)");
c.parseAndEval("library(RColorBrewer)");
c.parseAndEval("setwd('" + path + "')");
c.parseAndEval("data1=readLines('" + file + "')");
c.parseAndEval("data2 = sapply(data1,extractNoun,USE.NAMES=F)");
c.parseAndEval("data3 = unlist(data2)");
c.parseAndEval("data3=gsub('seoul','',data3)");
c.parseAndEval("data3=gsub('request','',data3)");
c.parseAndEval("data3=gsub('place','',data3)");
c.parseAndEval("data3=gsub('transportation','',data3)");
c.parseAndEval("data3=gsub(' ','',data3)");
c.parseAndEval("data3=gsub('-','',data3)");
c.parseAndEval("data3=gsub('OO','',data3)");
c.parseAndEval("write(unlist(data3),'seoul_2.txt')");
c.parseAndEval("data4 = read.table('seoul_2.txt')"); ########this is what blows me up
c.parseAndEval("wordcount=table(data4)");
c.parseAndEval("palete = brewer.pal(9,'Set3')");
c.parseAndEval(
"wordcloud(names(wordcount),freq = wordcount,scale=c(5,1),rot.per=0.25, min.freq = 1," +
" random.order=F, random.color = T, colors=palete)");
c.parseAndEval("savePlot('0517seoul.png', type = 'png')");
c.parseAndEval("dev.off()");
c.close();
}
}
as you notice from the code
c.parseAndEval("data4 = read.table('seoul_2.txt')"); => at rserve.WordCloud1.main(WordCloud1.java:30)
I have no idea why it can't read my text file despite the fact that it could write that file.
This is what Java Eclipse console keeps showing me
Exception in thread "main" org.rosuda.REngine.REngineException: eval failed
at org.rosuda.REngine.Rserve.RConnection.parseAndEval(RConnection.java:499)
at org.rosuda.REngine.REngine.parseAndEval(REngine.java:108)
at rserve.WordCloud1.main(WordCloud1.java:30)
Caused by: org.rosuda.REngine.Rserve.RserveException: eval failed
at org.rosuda.REngine.Rserve.RConnection.eval(RConnection.java:261)
at org.rosuda.REngine.Rserve.RConnection.parseAndEval(RConnection.java:497)
... 2 more
and this is what RStudio keeps showing me
Error: long vectors not supported yet: qap_encode.c:36
Fatal error: unable to initialize the JIT
I tried everything I could do to resolve this issue, but still I am on the same spot.

Static Java function imported with rJava doesn't work with tm_map()

I've prepared a class with a static method in Java 6, which I've exported to a JAR file:
package pl.poznan.put.stemutil;
public class Stemmer {
public static String stemText(String text) {
Set<String> c = new HashSet<String>();
...
return StringUtils.join(c, " ");
}
}
I import it to R with following code:
require(rJava)
.jinit("java/stem-util.jar")
stem = J("pl.poznan.put.stemutil.Stemmer")$stemText
Then, when I call it directly it works, e.g:
> stem("płotkami")
[1] "płotek płotka"
But when I'll try to use it with tm_map() function, something goes wrong:
> vc = VCorpus(vs, readerControl = list(language = "pl"))
> vc[[1]]
<<PlainTextDocument (metadata: 7)>>
mirki mirkówny zaczynam wolne jutra ( ͡° ͜ʖ ͡°) #pijzwykopem #piwozlidla
> vc = tm_map(vc, stem)
Komunikat ostrzegawczy:
In mclapply(content(x), FUN, ...) :
all scheduled cores encountered errors in user code
> vc[[1]]
[1] "Error in FUN(X[[1L]], ...) : \n Sorry, parameter type `NA' is ambiguous or not supported.\n"
attr(,"class")
[1] "try-error"
attr(,"condition")
<simpleError in FUN(X[[1L]], ...): Sorry, parameter type `NA' is ambiguous or not supported.>
What am I doing incorrectly?
Finally adding mc.cores parameter has worked for me. However, It's more a workaround, than a proper solution.
vc = tm_map(vc, content_transformer(stem), mc.cores=1)

Categories