Hanjie's Blog

一只有理想的羊驼

Hardware: MacBook Pro with Apple M1 Max OS: macOS Monterey 12.0.1

Install Xcode and Homebrew1

1
2
3
4
sudo xcodebuild -license
# accept the Xcode license

sudo xcode-select --install

Install Homebrew2:

1
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

If you would want to add the command brew after the installation is complete:

1
2
3
echo 'eval $(/opt/homebrew/bin/brew shellenv)' >> $HOME/.zprofile
eval "$(/opt/homebrew/bin/brew shellenv)"
source $HOME/.zprofile
1
2
3
4
5
brew update

brew -v
Homebrew 3.3.7
Homebrew/homebrew-core (git revision e1567b5f249; last commit 2021-12-13)

Install Miniforge

Virtual environments are a great way to separate different dependencies if you need different versions for different projects or if you don’t want to change your system path and its dependencies. One of the most popular packages to accomplish this is Anaconda, but anaconda is bloated and doesn’t always have the right packages for m1. Instead, we use miniforge, a community package that provides a minimalistic Anaconda install and uses the conda-forge branch to install packages. Conda-forge provides community packages for Anaconda which has a much larger library of arm64 compatible packages.3

1
2
brew install miniforge
conda init zsh

Checking:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
conda info

active environment : None
shell level : 0
user config file : /Users/luohanjie/.condarc
populated config files : /opt/homebrew/Caskroom/miniforge/base/.condarc
/Users/luohanjie/.condarc
conda version : 4.11.0
conda-build version : not installed
python version : 3.9.7.final.0
virtual packages : __osx=12.0.1=0
__unix=0=0
__archspec=1=arm64
base environment : /opt/homebrew/Caskroom/miniforge/base (writable)
conda av data dir : /opt/homebrew/Caskroom/miniforge/base/etc/conda
conda av metadata url : None
channel URLs : https://conda.anaconda.org/conda-forge/osx-arm64
https://conda.anaconda.org/conda-forge/noarch
package cache : /opt/homebrew/Caskroom/miniforge/base/pkgs
/Users/luohanjie/.conda/pkgs
envs directories : /opt/homebrew/Caskroom/miniforge/base/envs
/Users/luohanjie/.conda/envs
platform : osx-arm64
user-agent : conda/4.11.0 requests/2.26.0 CPython/3.9.7 Darwin/21.1.0 OSX/12.0.1
UID:GID : 501:20
netrc file : None
offline mode : False

conda常用命令4 1. conda --version #查看conda版本,验证是否安装 2. conda update --name base conda #更新至最新版本,也会更新其它相关包 3. conda update --all #更新所有包 4. conda update package_name #更新指定的包 5. conda create -n env_name package_name #创建名为env_name的新环境,并在该环境下安装名为package_name 的包,可以指定新环境的版本号,例如:conda create -n python2 python=python2.7 numpy pandas,创建了python2环境,python版本为2.7,同时还安装了numpy pandas包 6. source activate env_name #切换至env_name环境 7. source deactivate #退出环境 8. conda info -e #显示所有已经创建的环境 9. conda create --name new_env_name --clone old_env_name #复制old_env_name为new_env_name 10. conda remove --name env_name –-all #删除环境 11. conda list #查看所有已经安装的包 12. conda install package_name #在当前环境中安装包 13. conda install --name env_name package_name #在指定环境中安装包 14. conda remove -- name env_name package #删除指定环境中的包 15. conda remove package #删除当前环境中的包 16. conda create -n tensorflow_env tensorflow 17. conda activate tensorflow_env #conda 安装tensorflow的CPU版本 18. conda create -n tensorflow_gpuenv tensorflow-gpu 19. conda activate tensorflow_gpuenv #conda安装tensorflow的GPU版本 20. conda env remove -n env_name #采用第10条的方法删除环境失败时,可采用这种方法

Disable the automatic activation of the base environment:

1
conda config --set auto_activate_base false

Next we can set up a new virtual environment called cv with python 3.9.

1
2
3
4
5
conda create --name cv python=3.9
conda activate cv

python --version
Python 3.9.7

Install Numpty and TensorFlow5

1
2
3
4
conda install -c apple tensorflow-deps==2.7
python -m pip install tensorflow-macos==2.7 -i https://mirrors.aliyun.com/pypi/simple/
python -m pip install tensorflow-metal==0.3.0 -i https://mirrors.aliyun.com/pypi/simple/
conda install -y pandas scikit-learn jupyterlab

Check numpy version:

1
python -c "import numpy as np;print(np.__version__);np.show_config()"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
1.19.5
blas_info:
libraries = ['cblas', 'blas', 'cblas', 'blas']
library_dirs = ['/opt/homebrew/Caskroom/miniforge/base/envs/cv/lib']
include_dirs = ['/opt/homebrew/Caskroom/miniforge/base/envs/cv/include']
language = c
define_macros = [('HAVE_CBLAS', None)]
blas_opt_info:
define_macros = [('NO_ATLAS_INFO', 1), ('HAVE_CBLAS', None)]
libraries = ['cblas', 'blas', 'cblas', 'blas']
library_dirs = ['/opt/homebrew/Caskroom/miniforge/base/envs/cv/lib']
include_dirs = ['/opt/homebrew/Caskroom/miniforge/base/envs/cv/include']
language = c
lapack_info:
libraries = ['lapack', 'blas', 'lapack', 'blas']
library_dirs = ['/opt/homebrew/Caskroom/miniforge/base/envs/cv/lib']
language = f77
lapack_opt_info:
libraries = ['lapack', 'blas', 'lapack', 'blas', 'cblas', 'blas', 'cblas', 'blas']
library_dirs = ['/opt/homebrew/Caskroom/miniforge/base/envs/cv/lib']
language = c
define_macros = [('NO_ATLAS_INFO', 1), ('HAVE_CBLAS', None)]
include_dirs = ['/opt/homebrew/Caskroom/miniforge/base/envs/cv/include']

NumPy dropped support for using the Accelerate BLAS and LAPACK at version 1.20.0. According to the release notes for NumPy 1.21.1, these bugs have been resolved and building NumPy from source using the Accelerate framework on MacOS >= 11.3 is now possible again. How to build NumPy from source linked to Apple Accelerate framework

Testing the environment6:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# What version of Python do you have?
import sys

import tensorflow.keras
import pandas as pd
import sklearn as sk
import tensorflow as tf

print(f"Tensor Flow Version: {tf.__version__}")
print(f"Keras Version: {tensorflow.keras.__version__}")
print()
print(f"Python {sys.version}")
print(f"Pandas {pd.__version__}")
print(f"Scikit-Learn {sk.__version__}")
gpu = len(tf.config.list_physical_devices('GPU'))>0
print("GPU is", "available" if gpu else "NOT AVAILABLE")
1
2
3
4
5
6
7
8
Tensor Flow Version: 2.7.0
Keras Version: 2.7.0

Python 3.9.7 | packaged by conda-forge | (default, Sep 29 2021, 19:24:02)
[Clang 11.1.0 ]
Pandas 1.3.4
Scikit-Learn 1.0.1
GPU is available
New version
1
2
3
4
conda install -c apple tensorflow-deps
pip install tensorflow-macos
pip install tensorflow-metal
conda install -y pandas scikit-learn jupyterlab
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
╰─ python -c "import numpy as np;print(np.__version__);np.show_config()"
1.26.0
Build Dependencies:
blas:
detection method: pkgconfig
found: true
include directory: /opt/arm64-builds/include
lib directory: /opt/arm64-builds/lib
name: openblas64
openblas configuration: USE_64BITINT=1 DYNAMIC_ARCH=1 DYNAMIC_OLDER= NO_CBLAS=
NO_LAPACK= NO_LAPACKE= NO_AFFINITY=1 USE_OPENMP= SANDYBRIDGE MAX_THREADS=3
pc file directory: /usr/local/lib/pkgconfig
version: 0.3.23.dev
lapack:
detection method: pkgconfig
found: true
include directory: /opt/arm64-builds/include
lib directory: /opt/arm64-builds/lib
name: openblas64
openblas configuration: USE_64BITINT=1 DYNAMIC_ARCH=1 DYNAMIC_OLDER= NO_CBLAS=
NO_LAPACK= NO_LAPACKE= NO_AFFINITY=1 USE_OPENMP= SANDYBRIDGE MAX_THREADS=3
pc file directory: /usr/local/lib/pkgconfig
version: 0.3.23.dev
Compilers:
c:
commands: cc
linker: ld64
name: clang
version: 14.0.0
c++:
commands: c++
linker: ld64
name: clang
version: 14.0.0
cython:
commands: cython
linker: cython
name: cython
version: 3.0.2
Machine Information:
build:
cpu: aarch64
endian: little
family: aarch64
system: darwin
host:
cpu: aarch64
endian: little
family: aarch64
system: darwin
Python Information:
path: /private/var/folders/76/zy5ktkns50v6gt5g8r0sf6sc0000gn/T/cibw-run-4sgjw1qw/cp310-macosx_arm64/build/venv/bin/python
version: '3.10'
SIMD Extensions:
baseline:
- NEON
- NEON_FP16
- NEON_VFPV4
- ASIMD
found:
- ASIMDHP
not found:
- ASIMDFHM
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>> print(f"Tensor Flow Version: {tf.__version__}")
Tensor Flow Version: 2.14.0
>>> print(f"Keras Version: {tensorflow.keras.__version__}")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: module 'tensorflow.keras' has no attribute '__version__'
>>> print()

>>> print(f"Python {sys.version}")
Python 3.10.12 | packaged by conda-forge | (main, Jun 23 2023, 22:41:52) [Clang 15.0.7 ]
>>> print(f"Pandas {pd.__version__}")
Pandas 2.1.1
>>> print(f"Scikit-Learn {sk.__version__}")
Scikit-Learn 1.3.1
>>> gpu = len(tf.config.list_physical_devices('GPU'))>0
>>> print("GPU is", "available" if gpu else "NOT AVAILABLE")
GPU is available

Install FFmpeg

1
2
3
brew install ffmpeg@4

echo 'export PATH="/opt/homebrew/opt/ffmpeg/bin:$PATH"' >> ~/.zshrc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
ffmpeg -version

ffmpeg version 4.4.1 Copyright (c) 2000-2021 the FFmpeg developers
built with Apple clang version 13.0.0 (clang-1300.0.29.3)
configuration: --prefix=/opt/homebrew/Cellar/ffmpeg/4.4.1_3 --enable-shared --enable-pthreads --enable-version3 --cc=clang --host-cflags= --host-ldflags= --enable-ffplay --enable-gnutls --enable-gpl --enable-libaom --enable-libbluray --enable-libdav1d --enable-libmp3lame --enable-libopus --enable-librav1e --enable-librist --enable-librubberband --enable-libsnappy --enable-libsrt --enable-libtesseract --enable-libtheora --enable-libvidstab --enable-libvmaf --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libxvid --enable-lzma --enable-libfontconfig --enable-libfreetype --enable-frei0r --enable-libass --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libspeex --enable-libsoxr --enable-libzmq --enable-libzimg --disable-libjack --disable-indev=jack --enable-avresample --enable-videotoolbox
libavutil 56. 70.100 / 56. 70.100
libavcodec 58.134.100 / 58.134.100
libavformat 58. 76.100 / 58. 76.100
libavdevice 58. 13.100 / 58. 13.100
libavfilter 7.110.100 / 7.110.100
libavresample 4. 0. 0 / 4. 0. 0
libswscale 5. 9.100 / 5. 9.100
libswresample 3. 9.100 / 3. 9.100
libpostproc 55. 9.100 / 55. 9.100
1
2
3
4
5
6
7
8
9
10
11
12
ffmpeg@4 is keg-only, which means it was not symlinked into /opt/homebrew,
because this is an alternate version of another formula.

If you need to have ffmpeg@4 first in your PATH, run:
echo 'export PATH="/opt/homebrew/opt/ffmpeg@4/bin:$PATH"' >> ~/.zshrc

For compilers to find ffmpeg@4 you may need to set:
export LDFLAGS="-L/opt/homebrew/opt/ffmpeg@4/lib"
export CPPFLAGS="-I/opt/homebrew/opt/ffmpeg@4/include"

For pkg-config to find ffmpeg@4 you may need to set:
export PKG_CONFIG_PATH="/opt/homebrew/opt/ffmpeg@4/lib/pkgconfig"

Install QT5

1
2
brew install qt@5
echo 'export PATH="/opt/homebrew/opt/qt@5/bin:$PATH"' >> ~/.zshrc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
We agreed to the Qt open source license for you.
If this is unacceptable you should uninstall.

This version of Qt on Apple Silicon does not include QtWebEngine.

qt@5 is keg-only, which means it was not symlinked into /opt/homebrew,
because this is an alternate version of another formula.

If you need to have qt@5 first in your PATH, run:
echo 'export PATH="/opt/homebrew/opt/qt@5/bin:$PATH"' >> ~/.zshrc

For compilers to find qt@5 you may need to set:
export LDFLAGS="-L/opt/homebrew/opt/qt@5/lib"
export CPPFLAGS="-I/opt/homebrew/opt/qt@5/include"

For pkg-config to find qt@5 you may need to set:
export PKG_CONFIG_PATH="/opt/homebrew/opt/qt@5/lib/pkgconfig"

Install Gstreamer

1
brew install gstreamer gst-plugins-base

Install VTK

1
2
conda activate cv
conda install vtk

Build OpenCV

1
brew install wget cmake gcc

Download OpenCV source files:

1
2
3
4
5
6
wget -O opencv.zip https://github.com/opencv/opencv/archive/4.5.4.zip
wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/4.5.4.zip
unzip opencv.zip
unzip opencv_contrib.zip
cd opencv-4.5.4
mkdir build && cd build

Check PYTHON3_EXECUTABLE location7:

1
2
3
4
5
6
conda info -e

# conda environments:
#
base /opt/homebrew/Caskroom/miniforge/base
cv * /opt/homebrew/Caskroom/miniforge/base/envs/cv
1
2
which python3
/opt/homebrew/Caskroom/miniforge/base/envs/cv/bin/python3

so we get:

1
2
3
4
5
-D PYTHON3_LIBRARY=/opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/libpython3.9.dylib \
-D PYTHON3_INCLUDE_DIR=/opt/homebrew/Caskroom/miniforge/base/envs/cv/include/python3.9 \
-D PYTHON3_EXECUTABLE=/opt/homebrew/Caskroom/miniforge/base/envs/cv/bin/python3 \
-D PYTHON_DEFAULT_EXECUTABLE=/opt/homebrew/Caskroom/miniforge/base/envs/cv/bin/python3 \
-D PYTHON3_PACKAGES_PATH=/opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/python3.9/site-packages \

cmake:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
cmake -D CMAKE_SYSTEM_PROCESSOR=arm64 \
-D CMAKE_OSX_ARCHITECTURES=arm64 \
-D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D OPENCV_EXTRA_MODULES_PATH=/Users/luohanjie/Softwares/opencv_contrib-4.5.4/modules \
-D PYTHON3_LIBRARY=/opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/libpython3.9.dylib \
-D PYTHON3_INCLUDE_DIR=/opt/homebrew/Caskroom/miniforge/base/envs/cv/include/python3.9 \
-D PYTHON3_EXECUTABLE=/opt/homebrew/Caskroom/miniforge/base/envs/cv/bin/python3 \
-D PYTHON_DEFAULT_EXECUTABLE=/opt/homebrew/Caskroom/miniforge/base/envs/cv/bin/python3 \
-D PYTHON3_PACKAGES_PATH=/opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/python3.9/site-packages \
-D BUILD_opencv_python2=OFF \
-D BUILD_opencv_python3=ON \
-D INSTALL_PYTHON_EXAMPLES=OFF \
-D INSTALL_C_EXAMPLES=OFF \
-D OPENCV_ENABLE_NONFREE=ON \
-D BUILD_EXAMPLES=OFF \
-D WITH_OPENJPEG=ON \
-D WITH_IPP=OFF \
-D WITH_FFMPEG=ON \
-D WITH_GSTREAMER=ON \
-D WITH_OPENGL=ON \
-D WITH_VTK=ON \
-D VTK_DIR=/opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/cmake/vtk-9.1 \
-D WITH_QT=ON \
-D Qt5_DIR=$(brew --prefix qt5)/lib/cmake/Qt5 \
-D BUILD_opencv_java=OFF ..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
-- 
-- General configuration for OpenCV 4.5.4 =====================================
-- Version control: unknown
--
-- Extra modules:
-- Location (extra): /Users/luohanjie/Softwares/opencv_contrib-4.5.4/modules
-- Version control (extra): unknown
--
-- Platform:
-- Timestamp: 2022-08-30T02:00:42Z
-- Host: Darwin 21.6.0 arm64
-- CMake: 3.23.2
-- CMake generator: Unix Makefiles
-- CMake build tool: /usr/bin/make
-- Configuration: RELEASE
--
-- CPU/HW features:
-- Baseline: NEON FP16
--
-- C/C++:
-- Built as dynamic libs?: YES
-- C++ standard: 11
-- C++ Compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ (ver 13.1.6.13160021)
-- C++ flags (Release): -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG
-- C++ flags (Debug): -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -g -O0 -DDEBUG -D_DEBUG
-- C Compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
-- C flags (Release): -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG
-- C flags (Debug): -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -g -O0 -DDEBUG -D_DEBUG
-- Linker flags (Release): -Wl,-dead_strip
-- Linker flags (Debug): -Wl,-dead_strip
-- ccache: NO
-- Precompiled headers: NO
-- Extra dependencies: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/OpenGL.framework
-- 3rdparty dependencies:
--
-- OpenCV modules:
-- To be built: alphamat aruco barcode bgsegm bioinspired calib3d ccalib core datasets dnn dnn_objdetect dnn_superres dpm face features2d flann freetype fuzzy gapi hfs highgui img_hash imgcodecs imgproc intensity_transform line_descriptor mcc ml objdetect optflow phase_unwrapping photo plot python3 quality rapid reg rgbd saliency sfm shape stereo stitching structured_light superres surface_matching text tracking ts video videoio videostab viz wechat_qrcode xfeatures2d ximgproc xobjdetect xphoto
-- Disabled: java world
-- Disabled by dependency: -
-- Unavailable: cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev cvv hdf julia matlab ovis python2
-- Applications: tests perf_tests apps
-- Documentation: NO
-- Non-free algorithms: YES
--
-- GUI: QT5
-- QT: YES (ver 5.15.5 )
-- QT OpenGL support: YES (Qt5::OpenGL 5.15.5)
-- Cocoa: YES
-- OpenGL support: YES (/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/OpenGL.framework /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/OpenGL.framework)
-- VTK support: YES (ver 9.1.0)
--
-- Media I/O:
-- ZLib: zlib (ver 1.2.11)
-- JPEG: build-libjpeg-turbo (ver 2.1.0-62)
-- WEBP: build (ver encoder: 0x020f)
-- PNG: libpng (ver 1.6.37)
-- TIFF: libtiff (ver 42 / 4.2.0)
-- JPEG 2000: build (ver 2.4.0)
-- OpenEXR: build (ver 2.3.0)
-- HDR: YES
-- SUNRASTER: YES
-- PXM: YES
-- PFM: YES
--
-- Video I/O:
-- DC1394: NO
-- FFMPEG: YES
-- avcodec: YES (58.134.100)
-- avformat: YES (58.76.100)
-- avutil: YES (56.70.100)
-- swscale: YES (5.9.100)
-- avresample: YES (4.0.0)
-- GStreamer: YES (1.20.3)
-- AVFoundation: YES
--
-- Parallel framework: GCD
--
-- Trace: YES (with Intel ITT)
--
-- Other third-party libraries:
-- Lapack: YES (/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX12.3.sdk/System/Library/Frameworks/Accelerate.framework -lm -ldl)
-- Eigen: YES (ver 3.4.0)
-- Custom HAL: YES (carotene (ver 0.0.1))
-- Protobuf: build (3.5.1)
--
-- OpenCL: YES (no extra features)
-- Include path: NO
-- Link libraries: -framework OpenCL
--
-- Python 3:
-- Interpreter: /opt/homebrew/Caskroom/miniforge/base/envs/cv/bin/python3 (ver 3.9.7)
-- Libraries: /opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/libpython3.9.dylib (ver 3.9.7)
-- numpy: /opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/python3.9/site-packages/numpy/core/include (ver 1.19.5)
-- install path: /opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/python3.9/site-packages/cv2/python-3.9
--
-- Python (for build): /opt/homebrew/Caskroom/miniforge/base/envs/cv/bin/python3
--
-- Java:
-- ant: /opt/homebrew/bin/ant (ver 1.10.12)
-- JNI: /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk/Contents/Home/include /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk/Contents/Home/include/darwin /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk/Contents/Home/include
-- Java wrappers: NO
-- Java tests: NO
--
-- Install to: /usr/local
-- -----------------------------------------------------------------
--
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/luohanjie/Softwares/opencv-4.5.4/build_mac
1
2
make -j10
sudo make install

如果由于FFMPEG版本问题发生错误(OpenCV需要FFMPEG4版本),则通过下面去解决:

1
2
brew unlink ffmpeg
brew link ffmpeg@4

Sym-link OpenCV 4 on macOS to virtual environment site-packages:

1
2
3
4
mdfind cv2.cpython
/Users/luohanjie/Softwares/opencv-4.5.4/build/lib/python3/cv2.cpython-39-darwin.so
/usr/local/lib/python3.9/site-packages/cv2/python-3.9/cv2.cpython-39-darwin.so
...
1
2
3
4
5
conda info -e
# conda environments:
#
base /opt/homebrew/Caskroom/miniforge/base
cv * /opt/homebrew/Caskroom/miniforge/base/envs/cv
1
2
cd /opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/python3.9/site-packages
ln -s /Users/luohanjie/Softwares/opencv-4.5.4/build/lib/python3/cv2.cpython-39-darwin.so cv2.so

And test:

1
2
3
4
conda activate cv
python -c "import cv2;print(cv2.__version__);"

'4.5.4'

OpenGL8

1
brew install glew glfw

Oh My Zsh9 10

Check if using zsh:

1
2
echo $SHELL
/bin/zsh

Install Oh My Zsh:

1
sh -c "$(wget -O- https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"

Install the Powerlevel10k Theme:

1
git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k

Set ZSH_THEME="powerlevel10k/powerlevel10k" in ~/.zshrc.

Install Nerd Fonts:

1
2
brew tap homebrew/cask-fonts
brew install --cask font-hack-nerd-font

Open Terminal → Preferences → Profiles → Text, click Change under Font and select Hack family.

Restart Zsh. Type p10k configure if the configuration wizard doesn't start automatically.

Change settings for vscode

Open Command Pallete (Short Cut: F1), type settings and select Preferences: Open Settings (JSON):

1
"terminal.integrated.fontFamily": "Hack Nerd Font"

Install matplotlib

1
2
conda activate cv
conda install matplotlib

c#11

1
2
brew install --cask dotnet-sdk
brew install --cask mono-mdk
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
dotnet --version
6.0.401

mono --version
Mono JIT compiler version 6.12.0.182 (2020-02/6051b710727 Tue Jun 14 15:01:21 EDT 2022)
Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
TLS:
SIGSEGV: altstack
Notification: kqueue
Architecture: amd64
Disabled: none
Misc: softdebug
Interpreter: yes
LLVM: yes(610)
Suspend: hybrid
GC: sgen (concurrent by default)
1
2
which mono
/Library/Frameworks/Mono.framework/Versions/Current/Commands/mono

Install C# extension for Visual Studio Code(There may be some issues in 1.25.2, downgrade to 1.25.0 will fix the issue).

Go to File » Preferences » Settings in VS Code, set OmniSharp: Mono Path to the output of which mono, then disable OmniSharp: Use Modern Net.

如果运行Opencv程序时出现"ibpng warning: Application built with libpng-1.4.12 but running with 1.6.37"错误,可能是由于Mono造成的12

Mono.framework causes CMake to produce an incorrect build due to libpng and libjpeg.

CMake has this funny parameter called CMAKE_FIND_FRAMEWORK which is set by default to FIRST. This means that CMake will first look for files first in all framework directories, and only then in regular include directories. Funnily enough Mono.framework contains the headers for libjpeg and libpng. So, CMake finds the headers in Mono, but the library in the regular install location, e.g. /usr/local/lib and therefore a version mismatch happens.

Mono is a known menace (for some time brew doctor warned if Mono is installed that builds may fail). You can see this behavior if you create a CMakeLists.txt file with the single line find_package(JPEG), run cmake . and take a look at the paths in the generated CMakeCache.txt file.

The fix that definitively worked for me was to check out the project manually, add set(CMAKE_FIND_FRAMEWORK LAST) to CMakeLists.txt before the find_package calls and then run luarocks make. This way CMake found the headers in the right folder.

解决方法:先build opencv,然后再安装mono。

Build Android OpenCV

1
brew install openjdk@11 ant

For the system Java wrappers to find this JDK, symlink it with sudo ln -sfn /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk /Library/Java/JavaVirtualMachines/openjdk-11.jdk

openjdk@11 is keg-only, which means it was not symlinked into /opt/homebrew, because this is an alternate version of another formula.

If you need to have openjdk@11 first in your PATH, run: echo 'export PATH="/opt/homebrew/opt/openjdk@11/bin:$PATH"' >> ~/.zshrc

For compilers to find openjdk@11 you may need to set: export CPPFLAGS="-I/opt/homebrew/opt/openjdk@11/include"

1
2
3
echo 'export PATH="/opt/homebrew/opt/openjdk@11/bin:$PATH"' >> ~/.zshrc
echo 'export JAVA_HOME=/opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk/Contents/Home' >> ~/.zshrc
source ~/.zshrc
1
2
3
4
5
java -version

openjdk version "11.0.15" 2022-04-19
OpenJDK Runtime Environment Homebrew (build 11.0.15+0)
OpenJDK 64-Bit Server VM Homebrew (build 11.0.15+0, mixed mode)

Android Gradle 插件版本所需的 Gradle 版本:https://developer.android.google.cn/studio/releases/gradle-plugin

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
cd $OPENCV_SRC
mkdir build
cd build
export ANDROID_HOME=/Users/luohanjie/Library/Android/sdk
cmake -D CMAKE_TOOLCHAIN_FILE="/Users/luohanjie/Library/Android/sdk/ndk/24.0.8215888/build/cmake/android.toolchain.cmake" \
-D ANDROID_NDK="/Users/luohanjie/Library/Android/sdk/ndk/24.0.8215888" \
-D ANDROID_SDK="/Users/luohanjie/Library/Android/sdk" \
-D ANDROID_SDK_TOOLS="/Users/luohanjie/Library/Android/sdk/build-tools/33.0.0" \
-D ANDROID_ABI="arm64-v8a" \
-D ANDROID_STL=c++_shared \
-D ANDROID_NATIVE_API_LEVEL=android-29 \
-D ANDROID_PLATFORM=27 \
-D CMAKE_BUILD_TYPE=Release \
-D ANDROID_ARM_NEON=TRUE \
-D BUILD_TESTS=OFF \
-D BUILD_PERF_TESTS=OFF \
-D BUILD_ANDROID_EXAMPLES=OFF \
-D BUILD_ANDROID_PROJECTS=ON \
-D INSTALL_ANDROID_EXAMPLES='OFF' \
-D BUILD_opencv_python2=OFF \
-D BUILD_opencv_python3=OFF \
-D BUILD_DOCS=OFF \
-D BUILD_JAVA=ON \
-D BUILD_FAT_JAVA_LIB=ON \
-D ANDROID_PROJECTS_BUILD_TYPE='GRADLE' \
-D ANDROID_GRADLE_PLUGIN_VERSION='7.2.1' \
-D GRADLE_VERSION='7.5' \
-D ANT_EXECUTABLE=/opt/homebrew/bin/ant \
-D JAVA_INCLUDE_PATH=/opt/homebrew/opt/openjdk/include \
-D OPENCV_ENABLE_NONFREE=ON \
-D OPENCV_EXTRA_MODULES_PATH="/Users/luohanjie/Softwares/opencv_contrib-4.5.4/modules" ..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
-- General configuration for OpenCV 4.5.4 =====================================
-- Version control: unknown
--
-- Extra modules:
-- Location (extra): /Users/luohanjie/Softwares/opencv_contrib-4.5.4/modules
-- Version control (extra): unknown
--
-- Platform:
-- Timestamp: 2022-07-15T04:50:33Z
-- Host: Darwin 21.5.0 arm64
-- Target: Android 27 aarch64
-- CMake: 3.23.2
-- CMake generator: Unix Makefiles
-- CMake build tool: /usr/bin/make
-- Configuration: Release
--
-- CPU/HW features:
-- Baseline: NEON FP16
--
-- C/C++:
-- Built as dynamic libs?: NO
-- C++ standard: 11
-- C++ Compiler: /Users/luohanjie/Library/Android/sdk/ndk/24.0.8215888/toolchains/llvm/prebuilt/darwin-x86_64/bin/clang++ (ver 14.0.1)
-- C++ flags (Release): -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fexceptions -frtti -stdlib=libc++ -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winconsistent-missing-override -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -Wno-deprecated-enum-enum-conversion -Wno-deprecated-anon-enum-enum-conversion -fdiagnostics-show-option -Qunused-arguments -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG
-- C++ flags (Debug): -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fexceptions -frtti -stdlib=libc++ -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winconsistent-missing-override -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -Wno-deprecated-enum-enum-conversion -Wno-deprecated-anon-enum-enum-conversion -fdiagnostics-show-option -Qunused-arguments -fvisibility=hidden -fvisibility-inlines-hidden -g -fno-limit-debug-info -O0 -DDEBUG -D_DEBUG
-- C Compiler: /Users/luohanjie/Library/Android/sdk/ndk/24.0.8215888/toolchains/llvm/prebuilt/darwin-x86_64/bin/clang
-- C flags (Release): -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fexceptions -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winconsistent-missing-override -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -Wno-deprecated-enum-enum-conversion -Wno-deprecated-anon-enum-enum-conversion -fdiagnostics-show-option -Qunused-arguments -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG
-- C flags (Debug): -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fexceptions -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winconsistent-missing-override -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -Wno-deprecated-enum-enum-conversion -Wno-deprecated-anon-enum-enum-conversion -fdiagnostics-show-option -Qunused-arguments -fvisibility=hidden -fvisibility-inlines-hidden -g -fno-limit-debug-info -O0 -DDEBUG -D_DEBUG
-- Linker flags (Release): -Wl,--build-id=sha1 -Wl,--no-rosegment -Wl,--fatal-warnings -Qunused-arguments -Wl,--no-undefined -Wl,--as-needed
-- Linker flags (Debug): -Wl,--build-id=sha1 -Wl,--no-rosegment -Wl,--fatal-warnings -Qunused-arguments -Wl,--no-undefined -Wl,--as-needed
-- ccache: NO
-- Precompiled headers: NO
-- Extra dependencies: z dl m log
-- 3rdparty dependencies: libcpufeatures libprotobuf ade ittnotify libjpeg-turbo libwebp libpng libtiff libopenjp2 IlmImf quirc tegra_hal
--
-- OpenCV modules:
-- To be built: aruco barcode bgsegm bioinspired calib3d ccalib core datasets dnn dnn_objdetect dnn_superres dpm face features2d flann fuzzy gapi hfs highgui img_hash imgcodecs imgproc intensity_transform java line_descriptor mcc ml objdetect optflow phase_unwrapping photo plot quality rapid reg rgbd saliency shape stereo stitching structured_light superres surface_matching text tracking video videoio videostab wechat_qrcode xfeatures2d ximgproc xobjdetect xphoto
-- Disabled: world
-- Disabled by dependency: -
-- Unavailable: alphamat cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev cvv freetype hdf julia matlab ovis python2 python3 sfm ts viz
-- Applications: -
-- Documentation: NO
-- Non-free algorithms: YES
--
-- Android NDK: /Users/luohanjie/Library/Android/sdk/ndk/24.0.8215888 (ver 24.0.8215888)
-- Android ABI: arm64-v8a
-- STL type: c++_shared
-- Native API level: 27
-- Android SDK: /Users/luohanjie/Library/Android/sdk (tools: 33.0.0 build tools: 33.0.0)
--
-- GUI: NONE
--
-- Media I/O:
-- ZLib: z (ver 1.2.11)
-- JPEG: build-libjpeg-turbo (ver 2.1.0-62)
-- WEBP: build (ver encoder: 0x020f)
-- PNG: build (ver 1.6.37)
-- TIFF: build (ver 42 - 4.2.0)
-- JPEG 2000: build (ver 2.4.0)
-- OpenEXR: build (ver 2.3.0)
-- HDR: YES
-- SUNRASTER: YES
-- PXM: YES
-- PFM: YES
--
-- Video I/O:
--
-- Parallel framework: pthreads
--
-- Trace: YES (with Intel ITT)
--
-- Other third-party libraries:
-- Custom HAL: YES (carotene (ver 0.0.1))
-- Protobuf: build (3.5.1)
--
-- Python (for build): /opt/homebrew/bin/python3
--
-- Java: export all functions
-- ant: /opt/homebrew/bin/ant (ver )
-- Java wrappers: YES
-- Java tests: NO
--
-- Install to: /Users/luohanjie/Softwares/opencv-4.5.4/build_android/install
-- -----------------------------------------------------------------
--
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/luohanjie/Softwares/opencv-4.5.4/build_android
1
2
make -j20
make install

Eigen

1
brew install eigen

安装完成后,eigen文件夹位于/opt/homebrew/Cellar/eigen/3.4.0_1文件夹内,并非系统文件夹。

1
2
3
4
brew link --overwrite eigen

To relink, run:
brew unlink eigen && brew link eigen

运行后,会在 系统文件夹/usr/local/include文件夹下创建一个文件夹链接(名为eigen3)指向上面的真实eigen文件夹13

Python

1
2
3
4
5
6
7
8
9
10
11
which python3
/opt/homebrew/bin/python3

which python
python not found

echo "alias python=python3" >> ~/.zshrc
source ~/.zshrc

which python
python: aliased to python3

Build OpenCV 4.6.0 with FFmpeg 5.1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
brew link zlib
brew upgrade ffmpeg
ffmpeg -version

ffmpeg version 5.1.2 Copyright (c) 2000-2022 the FFmpeg developers
built with Apple clang version 14.0.0 (clang-1400.0.29.102)
configuration: --prefix=/opt/homebrew/Cellar/ffmpeg/5.1.2 --enable-shared --enable-pthreads --enable-version3 --cc=clang --host-cflags= --host-ldflags= --enable-ffplay --enable-gnutls --enable-gpl --enable-libaom --enable-libbluray --enable-libdav1d --enable-libmp3lame --enable-libopus --enable-librav1e --enable-librist --enable-librubberband --enable-libsnappy --enable-libsrt --enable-libtesseract --enable-libtheora --enable-libvidstab --enable-libvmaf --enable-libvorbis --enable-libvpx --enable-libwebp --enable-libx264 --enable-libx265 --enable-libxml2 --enable-libxvid --enable-lzma --enable-libfontconfig --enable-libfreetype --enable-frei0r --enable-libass --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libopenjpeg --enable-libspeex --enable-libsoxr --enable-libzmq --enable-libzimg --disable-libjack --disable-indev=jack --enable-videotoolbox --enable-neon
libavutil 57. 28.100 / 57. 28.100
libavcodec 59. 37.100 / 59. 37.100
libavformat 59. 27.100 / 59. 27.100
libavdevice 59. 7.100 / 59. 7.100
libavfilter 8. 44.100 / 8. 44.100
libswscale 6. 7.100 / 6. 7.100
libswresample 4. 7.100 / 4. 7.100
libpostproc 56. 6.100 / 56. 6.100
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
cmake -D CMAKE_SYSTEM_PROCESSOR=arm64 \
-D CMAKE_OSX_ARCHITECTURES=arm64 \
-D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D OPENCV_EXTRA_MODULES_PATH=/Users/luohanjie/Softwares/opencv_contrib/modules \
-D PYTHON3_LIBRARY=/opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/libpython3.9.dylib \
-D PYTHON3_INCLUDE_DIR=/opt/homebrew/Caskroom/miniforge/base/envs/cv/include/python3.9 \
-D PYTHON3_EXECUTABLE=/opt/homebrew/Caskroom/miniforge/base/envs/cv/bin/python3 \
-D PYTHON_DEFAULT_EXECUTABLE=/opt/homebrew/Caskroom/miniforge/base/envs/cv/bin/python3 \
-D PYTHON3_PACKAGES_PATH=/opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/python3.9/site-packages \
-D BUILD_opencv_python2=OFF \
-D BUILD_opencv_python3=ON \
-D INSTALL_PYTHON_EXAMPLES=OFF \
-D INSTALL_C_EXAMPLES=OFF \
-D OPENCV_ENABLE_NONFREE=ON \
-D BUILD_EXAMPLES=OFF \
-D WITH_OPENJPEG=ON \
-D WITH_IPP=OFF \
-D WITH_FFMPEG=ON \
-D WITH_GSTREAMER=ON \
-D WITH_OPENGL=ON \
-D WITH_VTK=ON \
-D VTK_DIR=/opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/cmake/vtk-9.1 \
-D WITH_QT=ON \
-D Qt5_DIR=$(brew --prefix qt5)/lib/cmake/Qt5 \
-D BUILD_opencv_java=OFF \
-D BUILD_ZLIB=OFF ..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
-- General configuration for OpenCV 4.6.0 =====================================
-- Version control: unknown
--
-- Extra modules:
-- Location (extra): /Users/luohanjie/Softwares/opencv_contrib/modules
-- Version control (extra): 9d84eae
--
-- Platform:
-- Timestamp: 2022-11-02T10:18:17Z
-- Host: Darwin 21.6.0 arm64
-- CMake: 3.24.2
-- CMake generator: Unix Makefiles
-- CMake build tool: /usr/bin/make
-- Configuration: RELEASE
--
-- CPU/HW features:
-- Baseline: NEON FP16
--
-- C/C++:
-- Built as dynamic libs?: YES
-- C++ standard: 11
-- C++ Compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ (ver 14.0.0.14000029)
-- C++ flags (Release): -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG
-- C++ flags (Debug): -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -g -O0 -DDEBUG -D_DEBUG
-- C Compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
-- C flags (Release): -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG
-- C flags (Debug): -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -g -O0 -DDEBUG -D_DEBUG
-- Linker flags (Release): -Wl,-dead_strip
-- Linker flags (Debug): -Wl,-dead_strip
-- ccache: NO
-- Precompiled headers: NO
-- Extra dependencies:
-- 3rdparty dependencies:
--
-- OpenCV modules:
-- To be built: alphamat aruco barcode bgsegm bioinspired calib3d ccalib core cvv datasets dnn dnn_objdetect dnn_superres dpm face features2d flann freetype fuzzy gapi hfs highgui img_hash imgcodecs imgproc intensity_transform line_descriptor mcc ml objdetect optflow phase_unwrapping photo plot python3 quality rapid reg rgbd saliency sfm shape stereo stitching structured_light superres surface_matching text tracking ts video videoio videostab viz wechat_qrcode xfeatures2d ximgproc xobjdetect xphoto
-- Disabled: java world
-- Disabled by dependency: -
-- Unavailable: cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev hdf julia matlab ovis python2
-- Applications: tests perf_tests apps
-- Documentation: NO
-- Non-free algorithms: YES
--
-- GUI: QT5
-- QT: YES (ver 5.15.5 )
-- QT OpenGL support: YES (Qt5::OpenGL 5.15.5)
-- Cocoa: YES
-- OpenGL support: YES (/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.0.sdk/System/Library/Frameworks/OpenGL.framework /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.0.sdk/System/Library/Frameworks/OpenGL.framework)
-- VTK support: YES (ver 9.1.0)
--
-- Media I/O:
-- ZLib: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.0.sdk/usr/lib/libz.tbd (ver 1.2.11)
-- JPEG: build-libjpeg-turbo (ver 2.1.2-62)
-- WEBP: build (ver encoder: 0x020f)
-- PNG: libpng (ver 1.6.37)
-- TIFF: libtiff (ver 42 / 4.2.0)
-- JPEG 2000: build (ver 2.4.0)
-- OpenEXR: OpenEXR::OpenEXR (ver 3.1.5)
-- HDR: YES
-- SUNRASTER: YES
-- PXM: YES
-- PFM: YES
--
-- Video I/O:
-- DC1394: NO
-- FFMPEG: YES
-- avcodec: YES (59.37.100)
-- avformat: YES (59.27.100)
-- avutil: YES (57.28.100)
-- swscale: YES (6.7.100)
-- avresample: NO
-- GStreamer: YES (1.20.3)
-- AVFoundation: YES
--
-- Parallel framework: GCD
--
-- Trace: YES (with Intel ITT)
--
-- Other third-party libraries:
-- Lapack: YES (/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.0.sdk/System/Library/Frameworks/Accelerate.framework -lm -ldl)
-- Eigen: YES (ver 3.4.0)
-- Custom HAL: YES (carotene (ver 0.0.1))
-- Protobuf: build (3.19.1)
--
-- OpenCL: YES (no extra features)
-- Include path: NO
-- Link libraries: -framework OpenCL
--
-- Python 3:
-- Interpreter: /opt/homebrew/Caskroom/miniforge/base/envs/cv/bin/python3 (ver 3.9.13)
-- Libraries: /opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/libpython3.9.dylib (ver 3.9.13)
-- numpy: /opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/python3.9/site-packages/numpy/core/include (ver 1.19.5)
-- install path: /opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/python3.9/site-packages/cv2/python-3.9
--
-- Python (for build): /opt/homebrew/Caskroom/miniforge/base/envs/cv/bin/python3
--
-- Java:
-- ant: /opt/homebrew/bin/ant (ver 1.10.12)
-- JNI: /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk/Contents/Home/include /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk/Contents/Home/include/darwin /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk/Contents/Home/include
-- Java wrappers: NO
-- Java tests: NO
--
-- Install to: /usr/local
-- -----------------------------------------------------------------
--
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/luohanjie/Softwares/opencv-4.6.0/build_mac
1
2
make j-20
sudo make install

注意opencv_contrib4.6.0tag版本可能会存在ceres问题,改用主分支解决。 BUILD_ZLIB可能会存在问题-D BUILD_ZLIB=OFF解决。 FFmpeg 5.1导致videoio问题,在modules/videoio/src/ffmpeg_codecs.hpp中添加#include <libavcodec/version.h>解决。

OpenCV 3.4.15

注意删掉opencv_contrib/modules目录下与opencv/modules同名字的文件夹。删掉opencv_contrib/modulesalphamatqualityintensity_transformxphotosfmcvvtrackinglibmv_lightmccxfeatures2drgbdximgprocfreetypearucobarcodewechat_qrcode文件夹。

opencv/CMakeLists.txt中添加set (CMAKE_CXX_STANDARD 11)

opencv/modules/core/include/opencv2/core/cvdef.h添加:

1
2
3
4
5
6
7
8
#ifndef CV_CONSTEXPR
# if __cplusplus >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900/*MSVS 2015*/)
# define CV_CONSTEXPR constexpr
# endif
#endif
#ifndef CV_CONSTEXPR
# define CV_CONSTEXPR
#endif
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
cmake -D CMAKE_SYSTEM_PROCESSOR=arm64 \
-D CMAKE_OSX_ARCHITECTURES=arm64 \
-D CMAKE_BUILD_TYPE=RELEASE \
-D ENABLE_CXX=1 \
-D CMAKE_INSTALL_PREFIX=/Users/luohanjie/Softwares/opencv-3.4.19/build_mac/install \
-D OPENCV_EXTRA_MODULES_PATH=/Users/luohanjie/Softwares/opencv_contrib/modules \
-D BUILD_opencv_python2=OFF \
-D BUILD_opencv_python3=OFF \
-D INSTALL_PYTHON_EXAMPLES=OFF \
-D INSTALL_C_EXAMPLES=OFF \
-D OPENCV_ENABLE_NONFREE=ON \
-D BUILD_EXAMPLES=OFF \
-D WITH_OPENJPEG=ON \
-D BUILD_PNG=ON \
-D WITH_IPP=OFF \
-D WITH_FFMPEG=OFF \
-D WITH_GSTREAMER=ON \
-D WITH_OPENGL=ON \
-D WITH_VTK=ON \
-D VTK_DIR=/opt/homebrew/Caskroom/miniforge/base/envs/tf/lib/cmake/vtk-9.1 \
-D WITH_QT=ON \
-D Qt5_DIR=$(brew --prefix qt5)/lib/cmake/Qt5 \
-D BUILD_opencv_java=OFF \
-D BUILD_ZLIB=OFF ..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
-- General configuration for OpenCV 3.4.15 =====================================
-- Version control: unknown
--
-- Extra modules:
-- Location (extra): /Users/luohanjie/Softwares/opencv_contrib/modules
-- Version control (extra): 4.7.0-31-g853144ef-dirty
--
-- Platform:
-- Timestamp: 2023-04-14T01:54:22Z
-- Host: Darwin 21.6.0 arm64
-- CMake: 3.24.2
-- CMake generator: Unix Makefiles
-- CMake build tool: /usr/bin/make
-- Configuration: RELEASE
--
-- CPU/HW features:
-- Baseline: NEON FP16
--
-- C/C++:
-- Built as dynamic libs?: YES
-- C++ Compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ (ver 14.0.0.14000029)
-- C++ flags (Release): -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG
-- C++ flags (Debug): -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -g -O0 -DDEBUG -D_DEBUG
-- C Compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
-- C flags (Release): -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG
-- C flags (Debug): -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -g -O0 -DDEBUG -D_DEBUG
-- Linker flags (Release): -Wl,-dead_strip
-- Linker flags (Debug): -Wl,-dead_strip
-- ccache: NO
-- Precompiled headers: NO
-- Extra dependencies: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.1.sdk/System/Library/Frameworks/OpenGL.framework
-- 3rdparty dependencies:
--
-- OpenCV modules:
-- To be built: alphamat aruco barcode bgsegm bioinspired calib3d ccalib core datasets dnn dnn_objdetect dnn_superres dpm face features2d flann freetype fuzzy hfs highgui img_hash imgcodecs imgproc intensity_transform line_descriptor mcc ml objdetect optflow phase_unwrapping photo plot quality rapid reg rgbd saliency sfm shape stereo stitching structured_light superres surface_matching text tracking ts video videoio videostab wechat_qrcode xfeatures2d ximgproc xobjdetect xphoto
-- Disabled: java world
-- Disabled by dependency: -
-- Unavailable: cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev cvv hdf julia matlab ovis python2 python3 viz
-- Applications: tests perf_tests apps
-- Documentation: NO
-- Non-free algorithms: YES
--
-- GUI:
-- QT: YES (ver 5.15.8)
-- QT OpenGL support: YES (Qt5::OpenGL 5.15.8)
-- Cocoa: YES
-- OpenGL support: YES (/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.1.sdk/System/Library/Frameworks/OpenGL.framework /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.1.sdk/System/Library/Frameworks/OpenGL.framework)
-- VTK support: NO
--
-- Media I/O:
-- ZLib: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.1.sdk/usr/lib/libz.tbd (ver 1.2.11)
-- JPEG: build-libjpeg-turbo (ver 2.1.0-62)
-- WEBP: build (ver encoder: 0x020f)
-- PNG: libpng (ver 1.6.37)
-- TIFF: libtiff (ver 42 / 4.2.0)
-- JPEG 2000: build (ver 1.900.1)
-- OpenEXR: build (ver 2.3.0)
-- HDR: YES
-- SUNRASTER: YES
-- PXM: YES
--
-- Video I/O:
-- DC1394: NO
-- GStreamer: YES
-- base: YES (ver 1.22.0)
-- video: YES (ver 1.22.0)
-- app: YES (ver 1.22.0)
-- riff: YES (ver 1.22.0)
-- pbutils: YES (ver 1.22.0)
-- AVFoundation: YES
--
-- Parallel framework: GCD
--
-- Trace: YES (with Intel ITT)
--
-- Other third-party libraries:
-- Lapack: YES (/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.1.sdk/System/Library/Frameworks/Accelerate.framework -lm -ldl)
-- Eigen: YES (ver 3.4.0)
-- Custom HAL: YES (carotene (ver 0.0.1))
-- Protobuf: build (3.5.1)
--
-- OpenCL: YES (no extra features)
-- Include path: NO
-- Link libraries: -framework OpenCL
--
-- Python (for build): /opt/homebrew/bin/python3
--
-- Java:
-- ant: /opt/homebrew/bin/ant (ver 1.10.12)
-- JNI: /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk/Contents/Home/include /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk/Contents/Home/include/darwin /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk/Contents/Home/include
-- Java wrappers: NO
-- Java tests: NO
--
-- Install to: /usr/local
-- -----------------------------------------------------------------
--
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/luohanjie/Softwares/opencv-3.4.15/build_mac

OpenCV 4.7.0

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
cmake -D CMAKE_SYSTEM_PROCESSOR=arm64 \
-D CMAKE_OSX_ARCHITECTURES=arm64 \
-D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D OPENCV_EXTRA_MODULES_PATH=/Users/luohanjie/Softwares/opencv_contrib/modules \
-D PYTHON3_LIBRARY=/opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/libpython3.9.dylib \
-D PYTHON3_INCLUDE_DIR=/opt/homebrew/Caskroom/miniforge/base/envs/cv/include/python3.9 \
-D PYTHON3_EXECUTABLE=/opt/homebrew/Caskroom/miniforge/base/envs/cv/bin/python3 \
-D PYTHON_DEFAULT_EXECUTABLE=/opt/homebrew/Caskroom/miniforge/base/envs/cv/bin/python3 \
-D PYTHON3_PACKAGES_PATH=/opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/python3.9/site-packages \
-D BUILD_opencv_python2=OFF \
-D BUILD_opencv_python3=ON \
-D INSTALL_PYTHON_EXAMPLES=OFF \
-D INSTALL_C_EXAMPLES=OFF \
-D OPENCV_ENABLE_NONFREE=ON \
-D BUILD_EXAMPLES=OFF \
-D WITH_OPENJPEG=ON \
-D BUILD_PNG=ON \
-D WITH_IPP=OFF \
-D WITH_FFMPEG=ON \
-D WITH_GSTREAMER=ON \
-D WITH_OPENGL=ON \
-D WITH_VTK=ON \
-D WITH_CAROTENE=ON \
-D VTK_DIR=/opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/cmake/vtk-9.1 \
-D WITH_QT=ON \
-D Qt5_DIR=$(brew --prefix qt5)/lib/cmake/Qt5 \
-D BUILD_opencv_java=OFF \
-D BUILD_ZLIB=OFF ..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
-- 
-- General configuration for OpenCV 4.7.0 =====================================
-- Version control: unknown
--
-- Extra modules:
-- Location (extra): /Users/luohanjie/Softwares/opencv_contrib/modules
-- Version control (extra): 4.7.0
--
-- Platform:
-- Timestamp: 2023-02-10T05:10:10Z
-- Host: Darwin 21.6.0 arm64
-- CMake: 3.24.2
-- CMake generator: Unix Makefiles
-- CMake build tool: /usr/bin/make
-- Configuration: RELEASE
--
-- CPU/HW features:
-- Baseline: NEON FP16
--
-- C/C++:
-- Built as dynamic libs?: YES
-- C++ standard: 11
-- C++ Compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ (ver 14.0.0.14000029)
-- C++ flags (Release): -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG
-- C++ flags (Debug): -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -g -O0 -DDEBUG -D_DEBUG
-- C Compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
-- C flags (Release): -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG
-- C flags (Debug): -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -g -O0 -DDEBUG -D_DEBUG
-- Linker flags (Release): -Wl,-dead_strip
-- Linker flags (Debug): -Wl,-dead_strip
-- ccache: NO
-- Precompiled headers: NO
-- Extra dependencies:
-- 3rdparty dependencies:
--
-- OpenCV modules:
-- To be built: alphamat aruco barcode bgsegm bioinspired calib3d ccalib core cvv datasets dnn dnn_objdetect dnn_superres dpm face features2d flann freetype fuzzy gapi hfs highgui img_hash imgcodecs imgproc intensity_transform line_descriptor mcc ml objdetect optflow phase_unwrapping photo plot python3 quality rapid reg rgbd saliency sfm shape stereo stitching structured_light superres surface_matching text tracking ts video videoio videostab viz wechat_qrcode xfeatures2d ximgproc xobjdetect xphoto
-- Disabled: java world
-- Disabled by dependency: -
-- Unavailable: cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev hdf julia matlab ovis python2
-- Applications: tests perf_tests apps
-- Documentation: NO
-- Non-free algorithms: YES
--
-- GUI: QT5
-- QT: YES (ver 5.15.8 )
-- QT OpenGL support: YES (Qt5::OpenGL 5.15.8)
-- Cocoa: YES
-- OpenGL support: YES (/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.1.sdk/System/Library/Frameworks/OpenGL.framework /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.1.sdk/System/Library/Frameworks/OpenGL.framework)
-- VTK support: YES (ver 9.1.0)
--
-- Media I/O:
-- ZLib: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.1.sdk/usr/lib/libz.tbd (ver 1.2.11)
-- JPEG: build-libjpeg-turbo (ver 2.1.3-62)
-- SIMD Support Request: YES
-- SIMD Support: YES
-- WEBP: build (ver encoder: 0x020f)
-- PNG: libpng (ver 1.6.37)
-- TIFF: libtiff (ver 42 / 4.2.0)
-- JPEG 2000: build (ver 2.4.0)
-- OpenEXR: OpenEXR::OpenEXR (ver 3.1.5)
-- HDR: YES
-- SUNRASTER: YES
-- PXM: YES
-- PFM: YES
--
-- Video I/O:
-- DC1394: NO
-- FFMPEG: YES
-- avcodec: YES (59.37.100)
-- avformat: YES (59.27.100)
-- avutil: YES (57.28.100)
-- swscale: YES (6.7.100)
-- avresample: NO
-- GStreamer: YES (1.22.0)
-- AVFoundation: YES
--
-- Parallel framework: GCD
--
-- Trace: YES (with Intel ITT)
--
-- Other third-party libraries:
-- Lapack: YES (/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.1.sdk/System/Library/Frameworks/Accelerate.framework -lm -ldl)
-- Eigen: YES (ver 3.4.0)
-- Custom HAL: YES (carotene (ver 0.0.1))
-- Protobuf: build (3.19.1)
--
-- OpenCL: YES (no extra features)
-- Include path: NO
-- Link libraries: -framework OpenCL
--
-- Python 3:
-- Interpreter: /opt/homebrew/Caskroom/miniforge/base/envs/cv/bin/python3 (ver 3.9.13)
-- Libraries: /opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/libpython3.9.dylib (ver 3.9.13)
-- numpy: /opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/python3.9/site-packages/numpy/core/include (ver 1.23.5)
-- install path: /opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/python3.9/site-packages/cv2/python-3.9
--
-- Python (for build): /opt/homebrew/Caskroom/miniforge/base/envs/cv/bin/python3
--
-- Java:
-- ant: /opt/homebrew/bin/ant (ver 1.10.12)
-- JNI: /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk/Contents/Home/include /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk/Contents/Home/include/darwin /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk/Contents/Home/include
-- Java wrappers: NO
-- Java tests: NO
--
-- Install to: /usr/local
-- -----------------------------------------------------------------
--
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/luohanjie/Softwares/opencv-4.7.0/build_mac
Build Android OpenCV
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
mkdir android_build
cd android_build
export ANDROID_HOME=/Users/luohanjie/Library/Android/sdk
cmake -D ANDROID_NDK="${ANDROID_HOME}/ndk/25.1.8937393" \
-D CMAKE_TOOLCHAIN_FILE="${ANDROID_HOME}/ndk/25.1.8937393/build/cmake/android.toolchain.cmake" \
-D ANDROID_SDK="${ANDROID_HOME}" \
-D ANDROID_SDK_TOOLS="${ANDROID_HOME}/build-tools/33.0.0" \
-D ANDROID_ABI="arm64-v8a" \
-D ANDROID_STL=c++_shared \
-D ANDROID_NATIVE_API_LEVEL=android-29 \
-D ANDROID_PLATFORM=29 \
-D CMAKE_BUILD_TYPE=Release \
-D ANDROID_ARM_NEON=TRUE \
-D BUILD_TESTS=OFF \
-D BUILD_PERF_TESTS=OFF \
-D BUILD_ANDROID_EXAMPLES=OFF \
-D BUILD_ANDROID_PROJECTS=OFF \
-D INSTALL_ANDROID_EXAMPLES='OFF' \
-D BUILD_opencv_python2=OFF \
-D BUILD_opencv_python3=OFF \
-D BUILD_DOCS=OFF \
-D BUILD_JAVA=OFF \
-D BUILD_FAT_JAVA_LIB=OFF \
-D OPENCV_ENABLE_NONFREE=ON \
-D OPENCV_EXTRA_MODULES_PATH=/Users/luohanjie/Softwares/opencv_contrib/modules \
-D BUILD_SHARED_LIBS=ON ..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
-- General configuration for OpenCV 4.7.0 =====================================
-- Version control: unknown
--
-- Extra modules:
-- Location (extra): /Users/luohanjie/Softwares/opencv_contrib/modules
-- Version control (extra): 4.7.0
--
-- Platform:
-- Timestamp: 2023-03-30T09:18:13Z
-- Host: Darwin 21.6.0 arm64
-- Target: Android 1 aarch64
-- CMake: 3.24.2
-- CMake generator: Unix Makefiles
-- CMake build tool: /usr/bin/make
-- Configuration: Release
--
-- CPU/HW features:
-- Baseline: NEON FP16
--
-- C/C++:
-- Built as dynamic libs?: YES
-- C++ standard: 11
-- C++ Compiler: /Users/luohanjie/Library/Android/sdk/ndk/25.1.8937393/toolchains/llvm/prebuilt/darwin-x86_64/bin/clang++ (ver 14.0.6)
-- C++ flags (Release): -g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winconsistent-missing-override -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -Wno-deprecated-enum-enum-conversion -Wno-deprecated-anon-enum-enum-conversion -fdiagnostics-show-option -Qunused-arguments -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG
-- C++ flags (Debug): -g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winconsistent-missing-override -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -Wno-deprecated-enum-enum-conversion -Wno-deprecated-anon-enum-enum-conversion -fdiagnostics-show-option -Qunused-arguments -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -fno-limit-debug-info -O0 -DDEBUG -D_DEBUG
-- C Compiler: /Users/luohanjie/Library/Android/sdk/ndk/25.1.8937393/toolchains/llvm/prebuilt/darwin-x86_64/bin/clang
-- C flags (Release): -g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winconsistent-missing-override -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -Wno-deprecated-enum-enum-conversion -Wno-deprecated-anon-enum-enum-conversion -fdiagnostics-show-option -Qunused-arguments -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG
-- C flags (Debug): -g -DANDROID -fdata-sections -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes -D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Winconsistent-missing-override -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -Wno-deprecated-enum-enum-conversion -Wno-deprecated-anon-enum-enum-conversion -fdiagnostics-show-option -Qunused-arguments -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -fno-limit-debug-info -O0 -DDEBUG -D_DEBUG
-- Linker flags (Release): -Wl,--build-id=sha1 -Wl,--no-rosegment -Wl,--fatal-warnings -Wl,--gc-sections -Wl,--no-undefined -Qunused-arguments -Wl,--gc-sections -Wl,--as-needed -Wl,--no-undefined
-- Linker flags (Debug): -Wl,--build-id=sha1 -Wl,--no-rosegment -Wl,--fatal-warnings -Wl,--gc-sections -Wl,--no-undefined -Qunused-arguments -Wl,--gc-sections -Wl,--as-needed -Wl,--no-undefined
-- ccache: NO
-- Precompiled headers: NO
-- Extra dependencies: dl m log
-- 3rdparty dependencies:
--
-- OpenCV modules:
-- To be built: aruco barcode bgsegm bioinspired calib3d ccalib core datasets dnn dnn_objdetect dnn_superres dpm face features2d flann fuzzy gapi hfs highgui img_hash imgcodecs imgproc intensity_transform line_descriptor mcc ml objdetect optflow phase_unwrapping photo plot quality rapid reg rgbd saliency shape stereo stitching structured_light superres surface_matching text tracking video videoio videostab wechat_qrcode xfeatures2d ximgproc xobjdetect xphoto
-- Disabled: world
-- Disabled by dependency: -
-- Unavailable: alphamat cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev cvv freetype hdf java julia matlab ovis python2 python3 sfm ts viz
-- Applications: -
-- Documentation: NO
-- Non-free algorithms: YES
--
-- Android NDK: /Users/luohanjie/Library/Android/sdk/ndk/25.1.8937393 (ver 25.1.8937393)
-- Android ABI: arm64-v8a
-- NDK toolchain: aarch64-linux-android-clang
-- STL type: c++_shared
-- Native API level: 29
-- Android SDK: not used, projects are not built
--
-- GUI: NONE
--
-- Media I/O:
-- ZLib: z (ver 1.2.12)
-- JPEG: build-libjpeg-turbo (ver 2.1.3-62)
-- SIMD Support Request: YES
-- SIMD Support: YES
-- WEBP: build (ver encoder: 0x020f)
-- PNG: build (ver 1.6.37)
-- TIFF: build (ver 42 - 4.2.0)
-- JPEG 2000: build (ver 2.4.0)
-- OpenEXR: build (ver 2.3.0)
-- HDR: YES
-- SUNRASTER: YES
-- PXM: YES
-- PFM: YES
--
-- Video I/O:
--
-- Parallel framework: pthreads
--
-- Trace: YES (with Intel ITT)
--
-- Other third-party libraries:
-- Custom HAL: YES (carotene (ver 0.0.1))
-- Protobuf: build (3.19.1)
--
-- Python (for build): /opt/homebrew/bin/python3
--
-- Install to: /Users/luohanjie/Softwares/opencv-4.7.0/build_android/install
-- -----------------------------------------------------------------
--
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/luohanjie/Softwares/opencv-4.7.0/build_android
1
2
make -j20
make install

重新配置一个Python3.10的环境

1
2
3
4
5
6
7
8
conda create --name tf python=3.10
conda activate tf

python --version
Python 3.10.9

pip --version
pip 23.0.1 from /opt/homebrew/Caskroom/miniforge/base/envs/tf/lib/python3.10/site-packages/pip (python 3.10)
Install Numpty and TensorFlow 2.1014
1
2
3
4
conda install -c apple tensorflow-deps==2.10
python -m pip install tensorflow-macos==2.10 -i https://mirrors.aliyun.com/pypi/simple/
python -m pip install tensorflow-metal==0.6.0 -i https://mirrors.aliyun.com/pypi/simple/
conda install -y pandas scikit-learn jupyterlab
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Python 3.10.9 | packaged by conda-forge | (main, Feb  2 2023, 20:26:08) [Clang 14.0.6 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>>
>>> import tensorflow.keras
>>> import pandas as pd
>>> import sklearn as sk
>>> import tensorflow as tf
>>>
>>> print(f"Tensor Flow Version: {tf.__version__}")
Tensor Flow Version: 2.10.0
>>> print(f"Keras Version: {tensorflow.keras.__version__}")
Keras Version: 2.10.0
>>> print()

>>> print(f"Python {sys.version}")
Python 3.10.9 | packaged by conda-forge | (main, Feb 2 2023, 20:26:08) [Clang 14.0.6 ]
>>> print(f"Pandas {pd.__version__}")
Pandas 1.5.3
>>> print(f"Scikit-Learn {sk.__version__}")
Scikit-Learn 1.2.2
>>> gpu = len(tf.config.list_physical_devices('GPU'))>0
>>> print("GPU is", "available" if gpu else "NOT AVAILABLE")
GPU is available
>>>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/env python3
# Source: https://keras.io/examples/mnist_cnn/
# Trains a simple convnet on the MNIST dataset.
#
# DOCS claim: 99.25% test accuracy after 12 epochs | 16 seconds per epoch on a GRID K520 GPU.
# keras actual:
# $ KERAS_BACKEND=tensorflow TF_CPP_MIN_LOG_LEVEL=1 time -p src/examples/keras/keras_example_mnist_cnn.py
# $ KERAS_BACKEND=theano THEANO_FLAGS=device=cuda0 time -p src/examples/keras/keras_example_mnist_cnn.py
# $ KERAS_BACKEND=cntk time -p src/examples/keras/keras_example_mnist_cnn.py # ImportError: libmpi_cxx.so.1
# Test accuracy: 99.11% | 78s/total - 6s/epoc - 101us/step | Using keras + Adadelta(learning_rate=1.0) + TensorFlow GPU backend
# Test accuracy: 99.05% |3844s/total - 300s/epoc - 5ms/step | Using keras + Adadelta(learning_rate=1.0) + Theano CPU backend
# Test accuracy: 84.19% | 68s/total - 5s/epoc - 87us/step | Using tf.keras + Adadelta(learning_rate=0.001) + TensorFlow GPU backend
#
# tf.keras:
#
# $ TF_CPP_MIN_LOG_LEVEL=3 time -p src/examples/keras/tf_keras_example_mnist_cnn.py # tf.keras + Adadelta(learning_rate=0.001)
# Epoch 12435 - 21 hours/total - 5s/epoc - 88us/sample - loss: 0.0295 - accuracy: 0.9909 - val_loss: 0.0273 - val_accuracy: 0.9916
#
# NOTE: Code exhibits (eventually garbage collected) memory leak, with python varying between 2 - 5 GB of RAM

from __future__ import print_function

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import backend as K
from tensorflow.keras.datasets import mnist
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.models import Sequential
from tensorflow.python.keras.utils.np_utils import to_categorical

batch_size = 128
num_classes = 10
epochs = 12

# input image dimensions
img_rows, img_cols = 28, 28

# the data, split between train and test sets
(x_train, y_train), (x_test, y_test) = mnist.load_data()

if K.image_data_format() == 'channels_first':
x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
x_test = x_test.reshape( x_test.shape[0], 1, img_rows, img_cols)
input_shape = (1, img_rows, img_cols)
else:
x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
x_test = x_test.reshape( x_test.shape[0], img_rows, img_cols, 1)
input_shape = (img_rows, img_cols, 1)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255
print('x_train shape:', x_train.shape)
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = to_categorical(y_train, num_classes)
y_test = to_categorical(y_test, num_classes)

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
activation='relu',
input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
# optimizer='adadelta', # broken on Apple M1 + tensorflow-macos + tensorflow-metal
optimizer='rmsprop', # WORKS default
metrics=['accuracy'])

model.fit(x_train, y_train,
batch_size=batch_size,
epochs=epochs,
verbose=1,
validation_data=(x_test, y_test))

score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz
11490434/11490434 [==============================] - 2s 0us/step
x_train shape: (60000, 28, 28, 1)
60000 train samples
10000 test samples
Metal device set to: Apple M1 Max

systemMemory: 32.00 GB
maxCacheSize: 10.67 GB

2023-03-13 18:18:36.941932: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:306] Could not identify NUMA node of platform GPU ID 0, defaulting to 0. Your kernel may not have been built with NUMA support.
2023-03-13 18:18:36.942055: I tensorflow/core/common_runtime/pluggable_device/pluggable_device_factory.cc:272] Created TensorFlow device (/job:localhost/replica:0/task:0/device:GPU:0 with 0 MB memory) -> physical PluggableDevice (device: 0, name: METAL, pci bus id: <undefined>)
2023-03-13 18:18:37.214532: W tensorflow/core/platform/profile_utils/cpu_utils.cc:128] Failed to get CPU frequency: 0 Hz
Epoch 1/12
2023-03-13 18:18:37.452601: I tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.cc:114] Plugin optimizer for device_type GPU is enabled.
469/469 [==============================] - ETA: 0s - loss: 0.2049 - accuracy: 0.93892023-03-13 18:18:44.950883: I tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.cc:114] Plugin optimizer for device_type GPU is enabled.
469/469 [==============================] - 8s 12ms/step - loss: 0.2049 - accuracy: 0.9389 - val_loss: 0.0498 - val_accuracy: 0.9846
Epoch 2/12
469/469 [==============================] - 5s 11ms/step - loss: 0.0689 - accuracy: 0.9789 - val_loss: 0.0381 - val_accuracy: 0.9870
Epoch 3/12
469/469 [==============================] - 6s 12ms/step - loss: 0.0507 - accuracy: 0.9846 - val_loss: 0.0326 - val_accuracy: 0.9890
Epoch 4/12
469/469 [==============================] - 5s 12ms/step - loss: 0.0420 - accuracy: 0.9873 - val_loss: 0.0286 - val_accuracy: 0.9911
Epoch 5/12
469/469 [==============================] - 5s 12ms/step - loss: 0.0362 - accuracy: 0.9887 - val_loss: 0.0275 - val_accuracy: 0.9911
Epoch 6/12
469/469 [==============================] - 5s 11ms/step - loss: 0.0333 - accuracy: 0.9902 - val_loss: 0.0309 - val_accuracy: 0.9904
Epoch 7/12
469/469 [==============================] - 5s 11ms/step - loss: 0.0301 - accuracy: 0.9911 - val_loss: 0.0292 - val_accuracy: 0.9910
Epoch 8/12
469/469 [==============================] - 5s 12ms/step - loss: 0.0273 - accuracy: 0.9919 - val_loss: 0.0335 - val_accuracy: 0.9905
Epoch 9/12
469/469 [==============================] - 5s 11ms/step - loss: 0.0264 - accuracy: 0.9922 - val_loss: 0.0365 - val_accuracy: 0.9895
Epoch 10/12
469/469 [==============================] - 5s 11ms/step - loss: 0.0249 - accuracy: 0.9926 - val_loss: 0.0302 - val_accuracy: 0.9910
Epoch 11/12
469/469 [==============================] - 6s 12ms/step - loss: 0.0243 - accuracy: 0.9928 - val_loss: 0.0328 - val_accuracy: 0.9903
Epoch 12/12
469/469 [==============================] - 5s 12ms/step - loss: 0.0228 - accuracy: 0.9929 - val_loss: 0.0313 - val_accuracy: 0.9906
Test loss: 0.031274374574422836
Test accuracy: 0.990600049495697
其他库
1
2
conda install pytorch torchvision torchaudio -c pytorch
conda install vtk matplotlib
Build OpenCV 4.7.0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
cmake -D CMAKE_SYSTEM_PROCESSOR=arm64 \
-D CMAKE_OSX_ARCHITECTURES=arm64 \
-D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D OPENCV_EXTRA_MODULES_PATH=/Users/luohanjie/Softwares/opencv_contrib/modules \
-D PYTHON3_LIBRARY=/opt/homebrew/Caskroom/miniforge/base/envs/tf/lib/libpython3.10.dylib \
-D PYTHON3_INCLUDE_DIR=/opt/homebrew/Caskroom/miniforge/base/envs/tf/include/python3.10 \
-D PYTHON3_EXECUTABLE=/opt/homebrew/Caskroom/miniforge/base/envs/tf/bin/python3 \
-D PYTHON_DEFAULT_EXECUTABLE=/opt/homebrew/Caskroom/miniforge/base/envs/tf/bin/python3 \
-D PYTHON3_PACKAGES_PATH=/opt/homebrew/Caskroom/miniforge/base/envs/tf/lib/python3.10/site-packages \
-D BUILD_opencv_python2=OFF \
-D BUILD_opencv_python3=ON \
-D INSTALL_PYTHON_EXAMPLES=OFF \
-D INSTALL_C_EXAMPLES=OFF \
-D OPENCV_ENABLE_NONFREE=ON \
-D BUILD_EXAMPLES=OFF \
-D WITH_OPENJPEG=ON \
-D BUILD_PNG=ON \
-D WITH_IPP=OFF \
-D WITH_FFMPEG=ON \
-D WITH_GSTREAMER=ON \
-D WITH_OPENGL=ON \
-D WITH_VTK=ON \
-D WITH_QT=ON \
-D Qt5_DIR=$(brew --prefix qt5)/lib/cmake/Qt5 \
-D BUILD_opencv_java=OFF \
-D BUILD_ZLIB=OFF ..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
-- General configuration for OpenCV 4.7.0 =====================================
-- Version control: unknown
--
-- Extra modules:
-- Location (extra): /Users/luohanjie/Softwares/opencv_contrib/modules
-- Version control (extra): 4.7.0-39-gccc27724
--
-- Platform:
-- Timestamp: 2023-05-18T08:45:40Z
-- Host: Darwin 21.6.0 arm64
-- CMake: 3.24.2
-- CMake generator: Unix Makefiles
-- CMake build tool: /usr/bin/make
-- Configuration: RELEASE
--
-- CPU/HW features:
-- Baseline: NEON FP16
--
-- C/C++:
-- Built as dynamic libs?: YES
-- C++ standard: 11
-- C++ Compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ (ver 14.0.0.14000029)
-- C++ flags (Release): -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG
-- C++ flags (Debug): -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -g -O0 -DDEBUG -D_DEBUG
-- C Compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
-- C flags (Release): -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG
-- C flags (Debug): -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -g -O0 -DDEBUG -D_DEBUG
-- Linker flags (Release): -Wl,-dead_strip
-- Linker flags (Debug): -Wl,-dead_strip
-- ccache: NO
-- Precompiled headers: NO
-- Extra dependencies:
-- 3rdparty dependencies:
--
-- OpenCV modules:
-- To be built: alphamat aruco barcode bgsegm bioinspired calib3d ccalib core cvv datasets dnn dnn_objdetect dnn_superres dpm face features2d flann freetype fuzzy gapi hdf hfs highgui img_hash imgcodecs imgproc intensity_transform line_descriptor mcc ml objdetect optflow phase_unwrapping photo plot python3 quality rapid reg rgbd saliency sfm shape stereo stitching structured_light superres surface_matching text tracking ts video videoio videostab viz wechat_qrcode xfeatures2d ximgproc xobjdetect xphoto
-- Disabled: java world
-- Disabled by dependency: -
-- Unavailable: cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev julia matlab ovis python2
-- Applications: tests perf_tests apps
-- Documentation: NO
-- Non-free algorithms: YES
--
-- GUI: QT5
-- QT: YES (ver 5.15.8 )
-- QT OpenGL support: YES (Qt5::OpenGL 5.15.8)
-- Cocoa: YES
-- OpenGL support: YES (/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.1.sdk/System/Library/Frameworks/OpenGL.framework /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.1.sdk/System/Library/Frameworks/OpenGL.framework)
-- VTK support: YES (ver 9.2.6)
--
-- Media I/O:
-- ZLib: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.1.sdk/usr/lib/libz.tbd (ver 1.2.11)
-- JPEG: build-libjpeg-turbo (ver 2.1.3-62)
-- SIMD Support Request: YES
-- SIMD Support: YES
-- WEBP: build (ver encoder: 0x020f)
-- PNG: libpng (ver 1.6.37)
-- TIFF: libtiff (ver 42 / 4.2.0)
-- JPEG 2000: build (ver 2.4.0)
-- OpenEXR: OpenEXR::OpenEXR (ver 3.1.7)
-- HDR: YES
-- SUNRASTER: YES
-- PXM: YES
-- PFM: YES
--
-- Video I/O:
-- DC1394: NO
-- FFMPEG: YES
-- avcodec: YES (60.3.100)
-- avformat: YES (60.3.100)
-- avutil: YES (58.2.100)
-- swscale: YES (7.1.100)
-- avresample: NO
-- GStreamer: NO
-- AVFoundation: YES
--
-- Parallel framework: GCD
--
-- Trace: YES (with Intel ITT)
--
-- Other third-party libraries:
-- Lapack: YES (/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.1.sdk/System/Library/Frameworks/Accelerate.framework -lm -ldl)
-- Eigen: YES (ver 3.4.0)
-- Custom HAL: YES (carotene (ver 0.0.1))
-- Protobuf: build (3.19.1)
--
-- OpenCL: YES (no extra features)
-- Include path: NO
-- Link libraries: -framework OpenCL
--
-- Python 3:
-- Interpreter: /opt/homebrew/Caskroom/miniforge/base/envs/tf/bin/python3 (ver 3.10.9)
-- Libraries: /opt/homebrew/Caskroom/miniforge/base/envs/tf/lib/libpython3.10.dylib (ver 3.10.9)
-- numpy: /opt/homebrew/Caskroom/miniforge/base/envs/tf/lib/python3.10/site-packages/numpy/core/include (ver 1.23.2)
-- install path: /opt/homebrew/Caskroom/miniforge/base/envs/tf/lib/python3.10/site-packages/cv2/python-3.10
--
-- Python (for build): /opt/homebrew/Caskroom/miniforge/base/envs/tf/bin/python3
--
-- Java:
-- ant: /opt/homebrew/bin/ant (ver 1.10.12)
-- JNI: /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk/Contents/Home/include /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk/Contents/Home/include/darwin /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk/Contents/Home/include
-- Java wrappers: NO
-- Java tests: NO
--
-- Install to: /usr/local
-- -----------------------------------------------------------------
--
-- Configuring done
-- Generating done
-- Build files have been written to: /Users/luohanjie/Softwares/opencv-4.7.0/build_mac_py310

OpenCV 4.8.1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
cmake -D CMAKE_SYSTEM_PROCESSOR=arm64 \
-D CMAKE_OSX_ARCHITECTURES=arm64 \
-D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D OPENCV_EXTRA_MODULES_PATH=/Users/luohanjie/Softwares/opencv_contrib/modules \
-D PYTHON3_LIBRARY=/opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/libpython3.10.dylib \
-D PYTHON3_INCLUDE_DIR=/opt/homebrew/Caskroom/miniforge/base/envs/cv/include/python3.10 \
-D PYTHON3_EXECUTABLE=/opt/homebrew/Caskroom/miniforge/base/envs/cv/bin/python3 \
-D PYTHON_DEFAULT_EXECUTABLE=/opt/homebrew/Caskroom/miniforge/base/envs/cv/bin/python3 \
-D PYTHON3_PACKAGES_PATH=/opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/python3.10/site-packages \
-D BUILD_opencv_python2=OFF \
-D BUILD_opencv_python3=ON \
-D INSTALL_PYTHON_EXAMPLES=OFF \
-D INSTALL_C_EXAMPLES=OFF \
-D OPENCV_ENABLE_NONFREE=ON \
-D BUILD_EXAMPLES=OFF \
-D WITH_OPENJPEG=ON \
-D BUILD_PNG=ON \
-D WITH_IPP=OFF \
-D WITH_FFMPEG=ON \
-D WITH_GSTREAMER=ON \
-D WITH_OPENGL=ON \
-D WITH_VTK=ON \
-D WITH_QT=ON \
-D Qt5_DIR=$(brew --prefix qt5)/lib/cmake/Qt5 \
-D BUILD_opencv_java=OFF \
-D BUILD_ZLIB=OFF ..
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
-- 
-- General configuration for OpenCV 4.8.1 =====================================
-- Version control: unknown
--
-- Extra modules:
-- Location (extra): /Users/luohanjie/Softwares/opencv_contrib/modules
-- Version control (extra): 4.8.1-25-g3af65e6c
--
-- Platform:
-- Timestamp: 2023-10-16T03:09:23Z
-- Host: Darwin 23.0.0 arm64
-- CMake: 3.27.6
-- CMake generator: Unix Makefiles
-- CMake build tool: /usr/bin/make
-- Configuration: RELEASE
--
-- CPU/HW features:
-- Baseline: NEON FP16
--
-- C/C++:
-- Built as dynamic libs?: YES
-- C++ standard: 11
-- C++ Compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/c++ (ver 15.0.0.15000040)
-- C++ flags (Release): -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -Wno-deprecated-copy -O3 -DNDEBUG -DNDEBUG
-- C++ flags (Debug): -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -Wno-deprecated-copy -g -O0 -DDEBUG -D_DEBUG
-- C Compiler: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/cc
-- C flags (Release): -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG
-- C flags (Debug): -fsigned-char -W -Wall -Wreturn-type -Wnon-virtual-dtor -Waddress -Wsequence-point -Wformat -Wformat-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wuninitialized -Wno-delete-non-virtual-dtor -Wno-unnamed-type-template-args -Wno-comment -fdiagnostics-show-option -Qunused-arguments -Wno-semicolon-before-method-body -ffunction-sections -fdata-sections -fvisibility=hidden -fvisibility-inlines-hidden -g -O0 -DDEBUG -D_DEBUG
-- Linker flags (Release): -Wl,-dead_strip
-- Linker flags (Debug): -Wl,-dead_strip
-- ccache: NO
-- Precompiled headers: NO
-- Extra dependencies:
-- 3rdparty dependencies:
--
-- OpenCV modules:
-- To be built: alphamat aruco bgsegm bioinspired calib3d ccalib core cvv datasets dnn dnn_objdetect dnn_superres dpm face features2d flann freetype fuzzy gapi hdf hfs highgui img_hash imgcodecs imgproc intensity_transform line_descriptor mcc ml objdetect optflow phase_unwrapping photo plot python3 quality rapid reg rgbd saliency sfm shape stereo stitching structured_light superres surface_matching text tracking ts video videoio videostab viz wechat_qrcode xfeatures2d ximgproc xobjdetect xphoto
-- Disabled: java world
-- Disabled by dependency: -
-- Unavailable: cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev julia matlab ovis python2
-- Applications: tests perf_tests apps
-- Documentation: NO
-- Non-free algorithms: YES
--
-- GUI: QT6
-- QT: YES (ver 6.5.2 )
-- QT OpenGL support: YES (Qt6::OpenGL )
-- Cocoa: YES
-- OpenGL support: YES (/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX14.0.sdk/System/Library/Frameworks/OpenGL.framework /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX14.0.sdk/System/Library/Frameworks/OpenGL.framework)
-- VTK support: YES (ver 9.2.6)
--
-- Media I/O:
-- ZLib: /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX14.0.sdk/usr/lib/libz.tbd (ver 1.2.12)
-- JPEG: build-libjpeg-turbo (ver 2.1.3-62)
-- SIMD Support Request: YES
-- SIMD Support: YES
-- WEBP: build (ver encoder: 0x020f)
-- PNG: libpng (ver 1.6.37)
-- TIFF: libtiff (ver 42 / 4.2.0)
-- JPEG 2000: build (ver 2.5.0)
-- OpenEXR: OpenEXR::OpenEXR (ver 3.2.1)
-- HDR: YES
-- SUNRASTER: YES
-- PXM: YES
-- PFM: YES
--
-- Video I/O:
-- DC1394: NO
-- FFMPEG: YES
-- avcodec: YES (60.3.100)
-- avformat: YES (60.3.100)
-- avutil: YES (58.2.100)
-- swscale: YES (7.1.100)
-- avresample: NO
-- GStreamer: YES (1.22.6)
-- AVFoundation: YES
--
-- Parallel framework: GCD
--
-- Trace: YES (with Intel ITT)
--
-- Other third-party libraries:
-- Lapack: YES (/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX14.0.sdk/System/Library/Frameworks/Accelerate.framework -lm -ldl)
-- Eigen: YES (ver 3.4.0)
-- Custom HAL: YES (carotene (ver 0.0.1))
-- Protobuf: build (3.19.1)
-- Flatbuffers: builtin/3rdparty (23.5.9)
--
-- OpenCL: YES (no extra features)
-- Include path: NO
-- Link libraries: -framework OpenCL
--
-- Python 3:
-- Interpreter: /opt/homebrew/Caskroom/miniforge/base/envs/cv/bin/python3 (ver 3.10.12)
-- Libraries: /opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/libpython3.10.dylib (ver 3.10.12)
-- numpy: /opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/python3.10/site-packages/numpy/core/include (ver 1.26.0)
-- install path: /opt/homebrew/Caskroom/miniforge/base/envs/cv/lib/python3.10/site-packages/cv2/python-3.10
--
-- Python (for build): /opt/homebrew/Caskroom/miniforge/base/envs/cv/bin/python3
--
-- Java:
-- ant: /opt/homebrew/bin/ant (ver 1.10.14)
-- Java: NO
-- JNI: /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk/Contents/Home/include /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk/Contents/Home/include/darwin /opt/homebrew/opt/openjdk@11/libexec/openjdk.jdk/Contents/Home/include
-- Java wrappers: NO
-- Java tests: NO
--
-- Install to: /usr/local
-- -----------------------------------------------------------------
--
-- Configuring done (29.0s)
-- Generating done (0.9s)
-- Build files have been written to: /Users/luohanjie/Softwares/opencv-4.8.1/build_mac

pytorch

1
2
conda activate cv
conda install pytorch torchvision torchaudio -c pytorch
1
2
3
4
5
6
7
8
9
10
11
python
Python 3.9.13 | packaged by conda-forge | (main, May 27 2022, 17:00:33)
[Clang 13.0.1 ] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import torch
>>> import math
>>> print(torch.backends.mps.is_available())
True
>>> print(torch.backends.mps.is_built())
True
>>>

To run PyTorch code on the GPU, use torch.device("mps") analogous to torch.device("cuda") on an Nvidia GPU. Hence, in this example, we move all computations to the GPU15:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
dtype = torch.float
device = torch.device("mps")

# Create random input and output data
x = torch.linspace(-math.pi, math.pi, 2000, device=device, dtype=dtype)
y = torch.sin(x)

# Randomly initialize weights
a = torch.randn((), device=device, dtype=dtype)
b = torch.randn((), device=device, dtype=dtype)
c = torch.randn((), device=device, dtype=dtype)
d = torch.randn((), device=device, dtype=dtype)

learning_rate = 1e-6
for t in range(2000):
# Forward pass: compute predicted y
y_pred = a + b * x + c * x ** 2 + d * x ** 3

# Compute and print loss
loss = (y_pred - y).pow(2).sum().item()
if t % 100 == 99:
print(t, loss)

# Backprop to compute gradients of a, b, c, d with respect to loss
grad_y_pred = 2.0 * (y_pred - y)
grad_a = grad_y_pred.sum()
grad_b = (grad_y_pred * x).sum()
grad_c = (grad_y_pred * x ** 2).sum()
grad_d = (grad_y_pred * x ** 3).sum()

# Update weights using gradient descent
a -= learning_rate * grad_a
b -= learning_rate * grad_b
c -= learning_rate * grad_c
d -= learning_rate * grad_d


print(f'Result: y = {a.item()} + {b.item()} x + {c.item()} x^2 + {d.item()} x^3')
1
Result: y = 0.9504813551902771 + 1.0364974737167358 x + -1.9110007286071777 x^2 + 0.7653123736381531 x^3

pyqt5 16

1
conda install pyqt5

or,

1
pip install pyqt5 --config-settings --confirm-license= --verbose

Rust

1
brew install rust
1
2
3
4
5
rustc --version
rustc 1.65.0

cargo --version
cargo 1.65.0 (4bc8f24d3 2022-10-20)

Point Cloud Library

1
brew install pcl
1
2
3
4
5
6
7
8
9
10
find_package(PCL REQUIRED)
if(PCL_FOUND)
message("PCL_INCLUDE_DIRS: ${PCL_INCLUDE_DIRS}")
message("PCL_LIBRARY_DIRS: ${PCL_LIBRARY_DIRS}")
message("PCL_LIBRARIES: ${PCL_LIBRARIES}")
message("PCL_COMPONENTS: ${PCL_COMPONENTS}")
message("PCL_VERSION: ${PCL_VERSION}")
else()
message("pcl not found")
endif()
1
2
3
4
5
[cmake] PCL_INCLUDE_DIRS: /opt/homebrew/include/pcl-1.13;/opt/homebrew/Cellar/eigen/3.4.0_1/include/eigen3;/opt/homebrew/include;/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX13.1.sdk/usr/include
[cmake] PCL_LIBRARY_DIRS: /opt/homebrew/lib
[cmake] PCL_LIBRARIES: pcl_common;pcl_kdtree;pcl_octree;pcl_search;pcl_sample_consensus;pcl_filters;pcl_io;pcl_features;pcl_ml;pcl_segmentation;pcl_visualization;pcl_surface;pcl_registration;pcl_keypoints;pcl_tracking;pcl_recognition;pcl_stereo;pcl_apps;pcl_outofcore;pcl_people;pcl_simulation;Boost::system;Boost::filesystem;Boost::iostreams;Boost::serialization;VTK::ChartsCore;VTK::CommonColor;VTK::CommonComputationalGeometry;VTK::CommonCore;VTK::CommonDataModel;VTK::CommonExecutionModel;VTK::CommonMath;VTK::CommonMisc;VTK::CommonTransforms;VTK::FiltersCore;VTK::FiltersExtraction;VTK::FiltersGeneral;VTK::FiltersGeometry;VTK::FiltersModeling;VTK::FiltersSources;VTK::ImagingCore;VTK::ImagingSources;VTK::InteractionImage;VTK::InteractionStyle;VTK::InteractionWidgets;VTK::IOCore;VTK::IOGeometry;VTK::IOImage;VTK::IOLegacy;VTK::IOPLY;VTK::RenderingAnnotation;VTK::RenderingCore;VTK::RenderingContext2D;VTK::RenderingLOD;VTK::RenderingFreeType;VTK::ViewsCore;VTK::ViewsContext2D;VTK::RenderingOpenGL2;VTK::RenderingContextOpenGL2;VTK::GUISupportQt;FLANN::FLANN;QHULL::QHULL
[cmake] PCL_COMPONENTS: pcl_common;pcl_kdtree;pcl_octree;pcl_search;pcl_sample_consensus;pcl_filters;pcl_io;pcl_features;pcl_ml;pcl_segmentation;pcl_visualization;pcl_surface;pcl_registration;pcl_keypoints;pcl_tracking;pcl_recognition;pcl_stereo;pcl_apps;pcl_outofcore;pcl_people;pcl_simulation
[cmake] PCL_VERSION: 1.13.1
"VTK::jsoncpp"错误

如果出现以下错误:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[cmake] CMake Error at /opt/homebrew/lib/cmake/vtk-9.2/VTK-targets.cmake:973 (set_target_properties):
[cmake] The link interface of target "VTK::jsoncpp" contains:
[cmake]
[cmake] JsonCpp::JsonCpp
[cmake]
[cmake] but the target was not found. Possible reasons include:
[cmake]
[cmake] * There is a typo in the target name.
[cmake] * A find_package call is missing for an IMPORTED target.
[cmake] * An ALIAS target is missing.
[cmake]
[cmake] Call Stack (most recent call first):
[cmake] /opt/homebrew/lib/cmake/vtk-9.2/vtk-config.cmake:138 (include)
[cmake] /opt/homebrew/share/pcl-1.13/PCLConfig.cmake:271 (find_package)
[cmake] /opt/homebrew/share/pcl-1.13/PCLConfig.cmake:320 (find_VTK)
[cmake] /opt/homebrew/share/pcl-1.13/PCLConfig.cmake:554 (find_external_library)
[cmake] tests/pcl/CMakeLists.txt:2 (find_package)

则在CMakeLists.txt中添加find_package(VTK REQUIRED)

1
2
3
4
5
6
7
8
9
10
11
12
13
find_package(VTK REQUIRED)
find_package(PCL REQUIRED)
find_package(OpenCV REQUIRED)

add_definitions(${PCL_DEFINITIONS})

include_directories(${PCL_INCLUDE_DIRS}
${OpenCV_INCLUDE_DIRS})

link_directories(${PCL_LIBRARY_DIRS} ${OpenCV_LIBRARY_DIRS} )

add_executable(depth_image_to_pointclouds depth_image_to_pointclouds.cpp)
target_link_libraries(depth_image_to_pointclouds ${PCL_LIBRARIES} ${OpenCV_LIBS} )

Pangolin

1
2
3
4
5
6
7
8
9
10
brew install gsl

git clone git@github.com:stevenlovegrove/Pangolin.git
cd Pangolin
./scripts/install_prerequisites.sh -m brew all
mkdir build
cd build
cmake ..
make -j20
sudo make install

Checking for existing SSH Keys1 2

1
2
$ ls -al ~/.ssh
# Lists the files in your .ssh directory, if they exist
If you don't already have an SSH key, generating a new SSH key and adding it to the ssh-agent
1
2
3
4
5
6
7
8
cd ~/
mkdir .ssh ; cd .ssh

# Make sure that the file permissions are set to read/write/execute only for the user
chmod go-rwx .ssh

# substituting in your GitHub email address.
ssh-keygen -t ed25519 -C "your_email@example.com"

Check:

1
2
3
4
5
6
ls -al
total 16
drwxr-xr-x 4 luohanjie staff 128 12 13 16:28 .
drwxr-x---+ 28 luohanjie staff 896 12 13 16:25 ..
-rw------- 1 luohanjie staff 411 12 13 16:28 id_ed25519
-rw-r--r-- 1 luohanjie staff 101 12 13 16:28 id_ed25519.pub

Adding your SSH key to the ssh-agent

Start the ssh-agent in the background:

1
2
eval "$(ssh-agent -s)"
Agent pid 2421

If you're using macOS Sierra 10.12.2 or later, you will need to modify your ~/.ssh/config file to automatically load keys into the ssh-agent and store passphrases in your keychain:

1
2
3
4
5
open ~/.ssh/config
The file /Users/luohanjie/.ssh/config does not exist.

# If the file doesn't exist, create the file.
touch ~/.ssh/config

Open your ~/.ssh/config file, then modify the file to contain the following lines. If your SSH key file has a different name or path than the example code, modify the filename or path to match your current setup.

Note: If you chose not to add a passphrase to your key, you should omit the UseKeychain line.

1
2
3
4
Host *
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_ed25519

Add your SSH private key to the ssh-agent and store your passphrase in the keychain. If you created your key with a different name, or if you are adding an existing key that has a different name, replace id_ed25519 in the command with the name of your private key file.

Note: The -K option is Apple's standard version of ssh-add, which stores the passphrase in your keychain for you when you add an SSH key to the ssh-agent. If you chose not to add a passphrase to your key, run the command without the -K option.

If you don't have Apple's standard version installed, you may receive an error. For more information on resolving this error, see "Error: ssh-add: illegal option -- K."

In MacOS Monterey (12.0), the -K and -A flags are deprecated and have been replaced by the --apple-use-keychain and --apple-load-keychain flags, respectively.

1
ssh-add -K ~/.ssh/id_ed25519

Adding a new SSH key to your GitHub account

Copy the SSH public key to your clipboard:

1
pbcopy < ~/.ssh/id_ed25519.pub

In the upper-right corner of any page, click your profile photo, then click Settings.

Setting

In the user settings sidebar, click SSH and GPG keys. Click New SSH key or Add SSH key. Paste your key into the "Key" field. Click Add SSH key. If prompted, confirm your GitHub password.

Setting Environment Variables

Open a shell and make sure there exist an NDK global variable set to the directory where you extracted the NDK.

1
2
3
4
5
sudo gedit ~/.bashrc

export ANDROID_SDK=<path to Android SDK directory>
export ANDROID_NDK=<path to Android NDK directory>
export PATH=$PATH:$ANDROID_SDK/tools:$ANDROID_SDK/platform-tools:$ANDROID_NDK
1
2
3
4
5
6
7
8
9
source ~/.bashrc
ndk-build --version

GNU Make 4.2.1
Built for x86_64-pc-linux-gnu
Copyright (C) 1988-2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Building
1
cd /libusb/android/jni

ndk-build 的默认值为 none。 您可以使用 Application.mk 文件中的 APP_STL 变量指定 c++_shared、c++static、> none 或 system。例如: APP_STL := c++_shared ndk-build 仅允许为您的应用选择一个运行时,并且只能在 Application.mk 中进行选择。

由于我们希望使用c++_shared,所以我修改/libusb/android/jni/Application.mk文件,添加APP_STL := c++_shared

1
ndk-build
0%