JAVACV : Webcam capturing using javacv - opencv

Tried to capture from a webcam using the JAVACV library. But it throws an UnsatisfiedLinkError.
Stack trace is as follows:
Exception in thread "main" java.lang.UnsatisfiedLinkError:
C:\Users\anooj\AppData\Local\Temp\javacpp7955905460040\jniopencv_core.dll: %1 is not a valid Win32 application
at java.lang.ClassLoader$NativeLibrary.load(Native Method)
at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1928)
at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1825)
at java.lang.Runtime.load0(Runtime.java:792)
at java.lang.System.load(System.java:1059)
at com.googlecode.javacpp.Loader.loadLibrary(Loader.java:418)
at com.googlecode.javacpp.Loader.load(Loader.java:368)
at com.googlecode.javacpp.Loader.load(Loader.java:315)
at com.googlecode.javacv.cpp.opencv_core.<clinit>(opencv_core.java:131)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at com.googlecode.javacpp.Loader.load(Loader.java:334)
at com.googlecode.javacv.cpp.opencv_imgproc.<clinit>(opencv_imgproc.java:96)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at com.googlecode.javacpp.Loader.load(Loader.java:334)
at com.googlecode.javacv.cpp.opencv_highgui.<clinit>(opencv_highgui.java:91)
at com.googlecode.javacv.OpenCVFrameGrabber.start(OpenCVFrameGrabber.java:170)
at javaapplication16.JavaApplication16.captureframe(JavaApplication16.java:24)
at javaapplication16.JavaApplication16.main(JavaApplication16.java:38)
Java Result: 1
Our code is below:
import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
import static com.googlecode.javacv.cpp.opencv_highgui.cvSaveImage;
public class JavaApplication16 {
/**
* #param args the command line arguments
*/
public static void captureframe()
{
OpenCVFrameGrabber grabber=new OpenCVFrameGrabber(0);
try
{
grabber.start();
IplImage img=grabber.grab();
if(img!=null)
{
cvSaveImage("capture.jpg", img);
}
}
catch(Exception ae)
{
ae.printStackTrace();
}
}
public static void main(String[] args) {
captureframe();
}
}

Make Sure you have installed Microsoft Visual C++ Redistributable
package and setup path variable correctly. Below link explains all
the necessary steps
http://opencvlover.blogspot.in/2012/04/javacv-setup-with-eclipse-on-windows-7.html
Use VideoInputFrameGrabber instead of OpncvFrameGrabber as suggested
in link below
http://code.google.com/p/javacv/wiki/Windows7AndOpenCV#I_cannot_capture_from_my_Webcam_using_opencv_highgui_or_OpenCVFr

Remember that the version of openCV and javaCV must match.
Download latest version openCV 2..46 http://opencv.org/downloads.html
and download the javacp https://code.google.com/p/javacv/downloads/list [Note: choose the javacv-0.6-cppjars.zip 85.0 MB]
In this case you will not get Exception in thread "main" java.lang.UnsatisfiedLinkError:
My Code is running successfully.

see this link to solve the error you got Link1
see this link for the program to capture the image from camera, save it in a JPG format and show it on a canvas Link2
hope it solves your query.

Related

Library migration to AndroidX

I'm using Paho MQTT library in my AndroidX application. I'm getting exception NoClassDefFoundError for Landroid/support/v4/content/LocalBroadcastManager. I found that library uses depricated import:
import android.support.v4.content.LocalBroadcastManager;
Function that rises exception:
private void registerReceiver(BroadcastReceiver receiver) {
IntentFilter filter = new IntentFilter();
filter.addAction(MqttServiceConstants.CALLBACK_TO_ACTIVITY);
LocalBroadcastManager.getInstance(myContext).registerReceiver(receiver, filter);
receiverRegistered = true;
}
How to solve this problem? Should I download source and recompile library? Why it is not already done in latest release?
Whole exception:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.eurbon.pahomqttclientexample, PID: 17368
java.lang.NoClassDefFoundError: Failed resolution of: Landroid/support/v4/content/LocalBroadcastManager;
at org.eclipse.paho.android.service.MqttAndroidClient.registerReceiver(MqttAndroidClient.java:450)
at org.eclipse.paho.android.service.MqttAndroidClient.connect(MqttAndroidClient.java:428)
at org.eclipse.paho.android.service.MqttAndroidClient.connect(MqttAndroidClient.java:334)
at paho.android.mqtt_example.MainActivity.MqttConnect(MainActivity.java:121)
at paho.android.mqtt_example.MainActivity.onCreate(MainActivity.java:63)
at android.app.Activity.performCreate(Activity.java:6679)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
Caused by: java.lang.ClassNotFoundException: Didn't find class "android.support.v4.content.LocalBroadcastManager" on path: DexPathList[[zip file "/data/app/com.eurbon.pahomqttclientexample-1/base.apk"],nativeLibraryDirectories=[/data/app/com.eurbon.pahomqttclientexample-1/lib/x86, /system/lib, /vendor/lib]]
at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
at org.eclipse.paho.android.service.MqttAndroidClient.registerReceiver(MqttAndroidClient.java:450) 
at org.eclipse.paho.android.service.MqttAndroidClient.connect(MqttAndroidClient.java:428) 
at org.eclipse.paho.android.service.MqttAndroidClient.connect(MqttAndroidClient.java:334) 
at paho.android.mqtt_example.MainActivity.MqttConnect(MainActivity.java:121) 
at paho.android.mqtt_example.MainActivity.onCreate(MainActivity.java:63) 
at android.app.Activity.performCreate(Activity.java:6679) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2618) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6119) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776) 
After migrating a project to AndroidX, I don't think you can use android.support.v* anymore. What if you try and use the content support library from androidx.core and not android.support.v4; I think that will resolve the issue for you.
import androidx.core.content.LocalBroadcastManager;
If you're using Android Studio the intellisense should be pretty helpful in resolving other dependency issues and/or other errors/warnings due to the AndroidX migration and the suggested change to support library providers.

Android: linking to opencv results in SIGBUS (signal SIGBUS: illegal alignment) when exception is thrown

I have to work with opencv in an android project. Everything worked fine until I recently had to use c++ exception_ptr as well.
Since then, the use of std::rethrow_exception causes a SIGBUS (signal SIGBUS: illegal alignment).
I created a minimal example to illustrate the problem. The example application only links to opencv 3.4.4 but does not use any opencv function. If you remove the linking to opencv in CMakeLists.txt the app works fine and doesn't crash. If you add it however, the app will crash as soon as the native method triggerException() is called.
In my implementation the example application calls this method if a button is pressed.
native-lib.cpp:
#include <jni.h>
#include <string>
#include <exception>
/*
* code based on: https://en.cppreference.com/w/cpp/error/exception_ptr
*/
std::string handle_eptr2(std::exception_ptr eptr)
{
try {
if (eptr) {
std::rethrow_exception(eptr);
}
} catch (const std::exception &e) {
return "Caught exception \"" + std::string(e.what()) + "\"\n";
}
return "Something went wrong";
}
extern "C" JNIEXPORT jstring JNICALL
Java_com_example_user_exceptiontest_MainActivity_triggerException(
JNIEnv *env,
jobject /* this */) {
std::exception_ptr eptr;
try {
std::string().at(1); // this generates an std::out_of_range
} catch(...) {
eptr = std::current_exception(); // capture
}
std::string res = handle_eptr2(eptr);
return env->NewStringUTF(res.c_str());
}
CMakeLists.txt
cmake_minimum_required(VERSION 3.4.1)
set(OPENCV_DIR $ENV{HOME}/lib/OpenCV-android-sdk/sdk )
include_directories(${OPENCV_DIR}/native/jni/include )
add_library( native-lib
SHARED
src/main/cpp/native-lib.cpp)
find_library( log-lib
log)
target_link_libraries(
native-lib
# Removing the following line will make everything work as expected (what() message is returned)
${OPENCV_DIR}/native/libs/${ANDROID_ABI}/libopencv_java3.so # <--- critical line
${log-lib})
build.gradle
To use exceptions and c++17 support, I added the following lines to the configuration that is created by android-studio.
externalNativeBuild {
cmake {
arguments '-DANDROID_TOOLCHAIN=clang',
'-DANDROID_STL=c++_shared'
cppFlags "-std=c++1z -frtti -fexceptions"
}
}
Stacktrace:
<unknown> 0x004c4e47432b2b01
___lldb_unnamed_symbol15856$$libopencv_java3.so 0x0000007f811c4a58
_Unwind_Resume_or_Rethrow 0x0000007f811c4fc8
__cxa_rethrow 0x0000007f81181e50
__gnu_cxx::__verbose_terminate_handler() 0x0000007f811b1580
__cxxabiv1::__terminate(void (*)()) 0x0000007f81181c54
std::terminate() 0x0000007f81181cc0
std::rethrow_exception(std::exception_ptr) 0x0000007f802db2cc
handle_eptr2(std::exception_ptr) native-lib.cpp:35
::Java_com_example_user_exceptiontest_MainActivity_triggerException(JNIEnv *, jobject) native-lib.cpp:58
While searching for a solution I looked at the opencv sources (https://github.com/opencv/opencv/blob/master/modules/core/src/parallel.cpp) and stumbled upon this code snippet:
#ifndef CV__EXCEPTION_PTR
# if defined(__ANDROID__) && defined(ATOMIC_INT_LOCK_FREE) && ATOMIC_INT_LOCK_FREE < 2
# define CV__EXCEPTION_PTR 0 // Not supported, details: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58938
I'd understand if this changes the behavior of opencv, but I don't get how this might influence code that does not use opencv at all.
EDIT: It is also worth mentioning that linking to opencv has no impact if I use this code directly (without jni) in a linux (x86_64) desktop setting (clang, libc++, opencv3.4.4). Thus, my conclusion that it is an android specific problem...
Does anyone has an idea how to solve that issue or what to try next?
Thanks a lot in advance!
Opencv is compiled with gnu runtime while you are using c++ stl. See One STL per app. You will need to either use gnustl (you will need to go back to ndk 15 for that) or build opencv with c++ stl.
In order to build opencv with c++_static you can try to follow comment in opencv bugtracker
cmake -GNinja -DINSTALL_ANDROID_EXAMPLES=ON
-DANDROID_EXAMPLES_WITH_LIBS=ON -DBUILD_EXAMPLES=ON -DBUILD_DOCS=OFF -DWITH_OPENCL=OFF -DWITH_IPP=ON -DCMAKE_TOOLCHAIN_FILE=${ANDROID_NDK}/build/cmake/android.toolchain.cmake
-DANDROID_TOOLCHAIN=clang "-DANDROID_STL=c++_static" -DANDROID_ABI=x86 -DANDROID_SDK_TARGET=18 ../opencv
Followed by
make && make install

Play a video with vlcj on a Mac

Hi I'm trying to get a video running with vlcj on a mac.
I tried several things but everywhere there is something wrong.
The Programm is starting up, but there is no video playing. Does anyone know how to handle vlcj on a mac?
My intentions are to play a rtsp stream on a mac with java. I tried it first with opencv and now vlcj but didn't succed.
Are there any good examples how to do that on a mac or does anyone know why it is not working?
Thanks
Code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import uk.co.caprica.vlcj.binding.LibVlc;
import uk.co.caprica.vlcj.component.EmbeddedMediaPlayerComponent;
import uk.co.caprica.vlcj.runtime.RuntimeUtil;
import com.sun.jna.Native;
import com.sun.jna.NativeLibrary;
public class VideoExample {
private final EmbeddedMediaPlayerComponent mediaPlayerComponent;
public static void main(final String[] args) {
uk.co.caprica.vlcj.binding.LibC.INSTANCE.setenv("VLC_PLUGIN_PATH", "/Applications/VLC.app/Contents/MacOS/plugins", 1);
NativeLibrary.addSearchPath(RuntimeUtil.getLibVlcLibraryName(), "/Applications/VLC.app/Contents/MacOS/lib");
Native.loadLibrary(RuntimeUtil.getLibVlcLibraryName(), LibVlc.class);
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new VideoExample(args);
}
});
}
private VideoExample(String[] args) {
JFrame frame = new JFrame("vlcj Tutorial");
mediaPlayerComponent = new EmbeddedMediaPlayerComponent();
frame.setContentPane(mediaPlayerComponent);
frame.setLocation(100, 100);
frame.setSize(500, 500);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
mediaPlayerComponent.getMediaPlayer().playMedia("/test.m4v");
}
}
Bug:
[main] INFO uk.co.caprica.vlcj.Info - vlcj: <version not available>
[main] INFO uk.co.caprica.vlcj.Info - java: 1.8.0_45 Oracle Corporation
[main] INFO uk.co.caprica.vlcj.Info - java home: /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home/jre
[main] INFO uk.co.caprica.vlcj.Info - os: Mac OS X 10.10.4 x86_64
[AWT-EventQueue-0] INFO uk.co.caprica.vlcj.binding.LibVlcFactory - vlc: 2.2.1 Terry Pratchett (Weatherwax), changeset 2.2.1-0-ga425c42
[AWT-EventQueue-0] INFO uk.co.caprica.vlcj.binding.LibVlcFactory - libvlc: /Applications/VLC.app/Contents/MacOS/lib/libvlc.dylib
JavaVM WARNING: JAWT_GetAWT must be called after loading a JVM
Exception in thread "AWT-EventQueue-0" java.lang.UnsatisfiedLinkError: Can't load JAWT
at com.sun.jna.Native.getWindowHandle0(Native Method)
at com.sun.jna.Native$AWT.getComponentID(Native.java:1879)
at com.sun.jna.Native.getComponentID(Native.java:253)
at uk.co.caprica.vlcj.player.embedded.videosurface.CanvasVideoSurface.attach(CanvasVideoSurface.java:76)
at uk.co.caprica.vlcj.player.embedded.DefaultEmbeddedMediaPlayer.attachVideoSurface(DefaultEmbeddedMediaPlayer.java:162)
at uk.co.caprica.vlcj.player.embedded.DefaultEmbeddedMediaPlayer.onBeforePlay(DefaultEmbeddedMediaPlayer.java:327)
at uk.co.caprica.vlcj.player.DefaultMediaPlayer.play(DefaultMediaPlayer.java:804)
at uk.co.caprica.vlcj.player.DefaultMediaPlayer.playMedia(DefaultMediaPlayer.java:265)
at uk.co.caprica.vlcj.player.DefaultMediaPlayer.playMedia(DefaultMediaPlayer.java:256)
at VideoExample.<init>(VideoExample.java:46)
at VideoExample.<init>(VideoExample.java:34)
at VideoExample$1.run(VideoExample.java:29)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
This is a well-known and well-documented issue with vlcj (and in fact other applications) on OSX with a JDK later than 1.6.
I know link-only answers are not the best, but there's way too much information on this problem to repeat here, so check https://github.com/caprica/vlcj/issues/205.
Essentially you can't use the embedded media player component since it relies on a heavyweight AWT component (a Canvas) to 'host' the video, and in JDK 1.7 and later on OSX there is no heavyweight AWT anymore.
So on OSX either use the so-called "direct" rendering approach with vlcj, or use JDK 1.6.
Thanks
Here is everything explained step by step
http://capricasoftware.co.uk/#/projects/vlcj/tutorial/direct-rendering
the rtsp stream works perfectly fine if you are ok with 3 seconds delay

dLibs - OpenKinect

Recently I got interested in dLibs, the Java wrapper for OpenKinect.
But I have difficulties in running the codes in eclipse; I've added the libraries based on what I think.
How to run the codes, say the example .pde files?
I've written sth like this to see how it works...
public class Test {
public static void main(String[] args) {
Kinect.loadLibrary( "C:/Users/admin/Dropbox/new_workspace/dLibs/", "freenect.dll" );
Kinect k= new Kinect(0);
System.out.println(k.isReady());
}
}
==========
But I get this error:
#_KINECT_ERROR___#
location: dLibs.freenect.FreenectLibrary.loadLibrary(FreenectLibrary.java:177)
message: Unable to load library : freenect.dll
message: path = "C:\Users\admin\Dropbox\new_workspace\dLibs/freenect.dll"
message: try 'MyKinect.loadLibrary( "your dll path/", "freenect.dll" )'
which the 177 line of the FreenectLibrary is about the loadLibrary(...) method.
Can anyone please help me with that?
I was running the same issue. Make sure you use the 64bit dll file. Also make sure about the path is correct, and the use of / !

why does XmlSlurper throw NumberFormatException?

I launch my Grails 2.1.5 app from an IDE with an exception breakpoint set for NumberFormatException (meaning that the application will break whenever this exception is thrown).
If I then execute the following code from the Grails console:
import groovy.util.*
import groovyx.net.http.*
def uri = 'http://ws.audioscrobbler.com/2.0/?artist=Yelle&mbid=f43d43c8-eedf-4628-99b0-04120e7124c8&method=artist.gettopalbums&api_key=6e331f856413a5e3dfc91ec41cea5415&limit=6'
XmlSlurper().parse(uri)
The exception breakpoint is triggered because of the following code in Long.parseLong
public static long parseLong(String s, int radix)
throws NumberFormatException
{
if (s == null) {
throw new NumberFormatException("null");
}
// rest of method omitted
}
However it seems that XmlSlurper().parse(uri) returns the expected value, so I guess this exception is handled somewhere, but I can't figure out where. I'm puzzled about why Long.parseLong is called with a null value for the first param. Is this a bug in XmlSlurper or just some strange implementation detail?
Update
As requested, here's the call stack. I'm using JDK 7 and Groovy 1.8.8. I tried debugging it myself, but as you can see, I'm missing a lot of the relevant source files.
at java.lang.Long.parseLong(Long.java:404)
at java.lang.Long.parseLong(Long.java:483)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1571)
at org.apache.xerces.impl.XMLEntityManager.setupCurrentEntity(Unknown Source:-1)
at org.apache.xerces.impl.XMLVersionDetector.determineDocVersion(Unknown Source:-1)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source:-1)
at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source:-1)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source:-1)
at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source:-1)
at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source:-1)
at groovy.util.XmlSlurper.parse(XmlSlurper.java:146)
at groovy.util.XmlSlurper.parse(XmlSlurper.java:212)
As far as I can tell, this file from the OpenJDK mercurial repository is the version of sun.net.www.protocol.http.HttpURLConnection that is in Java 7 update 25, and the relevant extract is
1570 try {
1571 cl = Long.parseLong(responses.findValue("content-length"));
1572 } catch (Exception exc) { };
so the NumberFormatException will be thrown (and immediately ignored) whenever an HTTP response doesn't have a Content-Length header.

Resources