Macbook M1编译安装Java OpenCV

OpenCV-4.8.0编辑安装

查询编译依赖

brew info opencv
Macbook M1编译安装Java OpenCV_第1张图片
确保所有需要模块都打上了✔,未打✔的需要使用`brew`进行安装

下载OpenCV源码

在此处下载OpenCV源代码,选择Source,点击此处下载opencv_contrib-4.8.0
Macbook M1编译安装Java OpenCV_第2张图片
或者使用如下命令,通过Terminal下载

brew install wget
wget -O opencv.zip https://github.com/opencv/opencv/archive/4.8.0.zip
unzip opencv.zip
wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/4.8.0.zip
unzip opencv_contrib.zip

编译安装

进入下载路径,并创建build文件夹

cd opencv-4.8.0
mkdir build && cd build

建立一个run.sh文件,并输入如下代码,其中BUILD_opencv_java设置为ONOPENCV_EXTRA_MODULES_PATH设置为下载的opencv_contribmodules路径

cmake \
-DCMAKE_SYSTEM_PROCESSOR=arm64 \
-DCMAKE_OSX_ARCHITECTURES=arm64 \
-DWITH_OPENJPEG=OFF \
-DWITH_IPP=OFF \
-D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local/opencv \
-D JAVA_INCLUDE_PATH=$JAVA_HOME/include \
-D BUILD_opencv_python2=OFF \
-D BUILD_opencv_java=ON \
-D INSTALL_PYTHON_EXAMPLES=OFF \
-D INSTALL_C_EXAMPLES=OFF \
-D BUILD_ZLIB=OFF \
-D OPENCV_ENABLE_NONFREE=ON \
-D OPENCV_EXTRA_MODULES_PATH=/Users/guoquanhao/Downloads/opencv_contrib-4.8.0/modules \
-D BUILD_EXAMPLES=ON ..

输入bash run.sh运行该命令,实现cmake
完成之后输入make -j8或者make实现make

make -j8

J之后的数字8表示我们将使用所有8个内核来运行Make命令。您可以根据可用的硬件调整J选项。根据您的硬件,这应该需要6 -12分钟。

最后输入sudo make install进行安装

sudo make install

完成之后会在两个地方出现jar文件和lib文件,一个是build路径

opencv-4.8.0/build/bin/opencv-480.jar
opencv-4.8.0/build/lib/libopencv_java480.dylib

一个是安装路径

/usr/local/opencv/share/java/opencv4/libopencv_java480.dylib
/usr/local/opencv/share/java/opencv4/opencv-480.jar 

测试验证

完成后,利用Idea创建如下示例代码

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

public class Main {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        Mat mat = Mat.eye( 3, 3, CvType.CV_8UC1 );
        System.out.println( "mat = " + mat.dump() );
    }
}

设置java library path

-Djava.library.path=/usr/local/opencv/share/java/opencv4


设置Libraries

启动运行输出如下

/Library/Java/JavaVirtualMachines/jdk-17.jdk/Contents/Home/bin/java -Djava.library.path=/usr/local/opencv/share/java/opencv4 -javaagent:/Applications/IntelliJ IDEA CE.app/Contents/lib/idea_rt.jar=63621:/Applications/IntelliJ IDEA CE.app/Contents/bin -Dfile.encoding=UTF-8 -classpath /Library/Java/JavaVirtualMachines/jdk-17.jdk/Contents/Home:/Users/guoquanhao/IdeaProjects/OpenCVTest/out/production/OpenCVTest:/usr/local/opencv/share/java/opencv4/opencv-460.jar Main
mat = [  1,   0,   0;
   0,   1,   0;
   0,   0,   1]

Process finished with exit code 0

OpenCV-4.6.0编译安装

与4.8.0一样但是有如下两点注意,在编译过程中肯能遇见的报错

  • 4.6.0需要安装ffmpeg@4,参见github和stackoverflow
brew install ffmpeg@4
brew unlink ffmpeg
brew link ffmpeg@4
  • 4.6.0中代码有两处小bug,如果没有修复,自行对比修复,参见知乎、github issue、github pull request

你可能感兴趣的:(模型部署,java,opencv)