Setting up OpenCV for Java via Maven
Updated: Dec 18, 2021
When you learn about OpenCV, you’ll often hit up on OpenCV for Python or C++, but not Java. I can understand that OpenCV is a glorified NumPy extension for Python and OpenCV C++ is very fast. However, it’s possible that you have a legit need to use Java instead of Python or C++.
In a professional setting, Java users are likely to use Apache Maven to allow everyone to get the same version of each software without causing build and run issues. Sure, you can always install the library and setup the CLASSPATH to point at OpenCV, but I find it better to use Maven to handle the libraries. Just note that there is no official Maven repository for OpenCV at the time of writing, but there been others that have uploaded alternative repositories.
Repository for OpenCV 2
For those that are using OpenCV 2 and Java, you’d want to use the nu.pattern repository. Here is the line of code needed to import OpenCV:
<!-- https://mvnrepository.com/artifact/nu.pattern/opencv --> <dependency> <groupId>nu.pattern</groupId> <artifactId>opencv</artifactId> <version>2.4.9-4</version> </dependency
Repository for OpenCV 3
For those needing to use OpenCV 3, the repository will be different. There is no nu.pattern equivalent version for OpenCV 3. You will need to use the following repository instead:
<!-- https://mvnrepository.com/artifact/org.openpnp/opencv --> <dependency> <groupId>org.openpnp</groupId> <artifactId>opencv</artifactId> <version>3.4.2-0</version> </dependency>
Repository for OpenCV 4
Yes. There will be an OpenCV 4 being released soon. As a result, don’t expect one for OpenCV 4 just yet. If you’re interested in installing an early release of OpenCV 4 for Python, Adrien Rosebrock has posted some instructions for Mac OS X and Ubuntu users.
Loading the OpenCV Library
After adding the repository to your Maven file, you need to load the library for use. Normally, you would use the line:
However, this method won’t work as it relies on the OpenCV libraries actually being installed. Instead, you need to do the following:
nu.pattern.OpenCV.loadShared(); nu.pattern.OpenCV.loadLocally(); // Use in case loadShared() doesn't work
Once you call one of these methods, you should be able to use OpenCV normally. OpenCV Java is akin to OpenCV C++, so you should be able to transfer some of the knowledge over to the other programming language.