brew info opencv
在此处下载OpenCV源代码,选择Source,点击此处下载opencv_contrib-4.8.0
或者使用如下命令,通过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
设置为ON
,OPENCV_EXTRA_MODULES_PATH
设置为下载的opencv_contrib
的modules
路径
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
与4.8.0一样但是有如下两点注意,在编译过程中肯能遇见的报错
brew install ffmpeg@4
brew unlink ffmpeg
brew link ffmpeg@4