环境
- macOS 11.6.5
- CLion 2022.1
- OpenCV 4.5
视频看这里
Youtube
Bilibili
安装brew
Homebrew
是 macOS
上的一个包管理器,类似于 ubuntu
系统中的 apt-get
,通过它可以很方便的安装软件,官方网址是 https://brew.sh。
首先,终端中输入 xcode-select --install
,通过它来安装 CLT for Xcode
然后,使用官方的脚本进行安装,在终端中执行命令
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
如果出现在终端中无法解析域名的错误,可以直接在浏览器中打开 https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh,将文件内容拷贝下来,存储在脚本文件中,然后执行它
改用国内的清华源
# 可以将环境变量写入~/.bash_profile文件中
export HOMEBREW_CORE_GIT_REMOTE="https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-core.git"
brew tap --custom-remote --force-auto-update homebrew/core https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-core.git
brew tap --custom-remote --force-auto-update homebrew/cask https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-cask.git
brew tap --custom-remote --force-auto-update homebrew/cask-fonts https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-cask-fonts.git
brew tap --custom-remote --force-auto-update homebrew/cask-drivers https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-cask-drivers.git
brew tap --custom-remote --force-auto-update homebrew/cask-versions https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-cask-versions.git
brew tap --custom-remote --force-auto-update homebrew/command-not-found https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-command-not-found.git
brew update
安装opencv
使用 homebrew
来安装 opencv
brew install opencv
默认安装的是最新的版本,如果想要安装 opencv3
,可以这样
brew install opencv@3
如果是更古老的 opencv2
版本
brew install opencv@2
如果在安装过程出现类似下面的错误提示
==> Searching for similarly named formulae...
Error: No similarly named formula found.
Error: No available formula or cask with the name "opencv".
==> Searching for a previously deleted formula (in the last month)...
Error: No previously deleted formula found.
==> Searching taps on GitHub...
Error: No formula found in taps.
Error:No available formula with the name "opencv"
是因为之前的 homebrew-core
代码下载出现了问题,解决方法是
rm -rf /usr/local/Homebrew/Library/Taps/homebrew/homebrew-core
brew update
这里再列举一些常见的 brew
命令
# 卸载
brew uninstall opencv
# 查找软件包
brew search opencv
# 更新版本
brew upgrade opencv
# 更新homebrew
brew update
# 查看安装列表
brew list
验证安装
这里使用 CLion
集成开发环境来验证,新建一个项目
编译器这里都选择默认
项目创建后,修改 CMakeLists.txt
文件
cmake_minimum_required(VERSION 3.22)
project(HelloOpenCV)
set(CMAKE_CXX_STANDARD 11)
find_package(OpenCV)
include_directories(${OpenCV_INCLUDE_DIRS})
add_executable(HelloOpenCV main.cpp)
target_link_libraries(HelloOpenCV ${OpenCV_LIBS})
然后,修改源码文件 main.cpp
,以显示一张图片为例
#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main() {
Mat srcImage = imread("Lenna.png");
if (!srcImage.data) {
std::cout << "Image not loaded";
return -1;
}
imshow("image", srcImage);
waitKey(0);
return 0;
}
最后,将测试图片拷贝到目录 cmake-build-debug
,再运行项目