Kotlin + OpenCV + macOS + MacPorts

I saw this very useful post by Simon Hoffman on how to set up Kotlin and OpenCV.–tornadofx–opencv–fun–39e5

Here is an alternate approach (I’m not adding TornadoFX/JavaFX in this).

1. (After updating and upgrading your MacPorts) install opencv with java:

sudo port install opencv +java

This will install the OpenCV library (jar and dylib) to:


2. Now create a new Kotlin project in IntelliJ IDEA

3. Add the OpenCV dependency:

File > Project Structure > Modules > Dependencies > + > jars or directories > Navigate to /opt/local/share/OpenCV/java > select the OpenCV jar file – for me it was opencv-348.jar

4. Create a new Kotlin file (I named mine TestOpenCVSetup.kt) to test the installation – paste the following code (taken from Simon Hoffman’s post):

import org.opencv.core.Core
import org.opencv.core.CvType
import org.opencv.core.Mat

fun main() {

    val mat = Mat.eye(5, 5, CvType.CV_8UC1)
    println("mat = ${mat.dump()}")

If you’ve set up the dependency properly, there will be no errors.

5. Now click the green play button in the gutter of fun main()

You should get an error:

Exception in thread "main" java.lang.UnsatisfiedLinkError: no opencv_java348 in java.library.path: [/Users/your_user_name/Library/Java/Extensions, /Library/Java/Extensions, /Network/Library/Java/Extensions, /System/Library/Java/Extensions, /usr/lib/java, .]
	at java.base/java.lang.ClassLoader.loadLibrary(
	at java.base/java.lang.Runtime.loadLibrary0(
	at java.base/java.lang.System.loadLibrary(
	at TestOpenCVSetupKt.main(TestOpenCVSetup.kt:7)
	at TestOpenCVSetupKt.main(TestOpenCVSetup.kt)

6. Now you have a few options to fix the error.

One option is to copy the libopencv_java348.dylib file from /opt/local/share/OpenCV/java to your user Java libraries /Users/your_user_name/Library/Java/Extensions.

The Java/Extensions folders may not be present so you can create them (mkdir or Cmd + Shift + N).

7. Re-run the program and you should get the following output:

mat = [  1,   0,   0,   0,   0;
   0,   1,   0,   0,   0;
   0,   0,   1,   0,   0;
   0,   0,   0,   1,   0;
   0,   0,   0,   0,   1]

Process finished with exit code 0