我按照本教程在 Macbook M1 中构建了 OpenCV-4.5.2:https://sayak.dev/install-opencv-m1。它在 Python 中工作正常,但当我在 C++ 中使用时
#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
int main()
{
cv::Mat img = cv::imread("avatar.jpeg");
return 0;
}
它在 cv::Mat 中给出错误
Undefined symbols for architecture arm64:
"cv::Mat::~Mat()", referenced from:
_main in main.cpp.o
"cv::imread(std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> > const&, int)", referenced from:
_main in main.cpp.o
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make[3]: *** [imgproc] Error 1
make[2]: *** [CMakeFiles/imgproc.dir/all] Error 2
make[1]: *** [CMakeFiles/imgproc.dir/rule] Error 2
make: *** [imgproc] Error 2
几个小时后,我找不到问题所在。有谁能够帮助我?谢谢!
P/S:作为补充,这是我的 CMakeLists.txt
cmake_minimum_required(VERSION 3.19)
project(imgproc)
set(CMAKE_CXX_STANDARD 14)
# Set the location of the OpenCV directory
set(OpenCV_DIR "/usr/local/include/opencv4")
# Find OpenCV library
find_package( OpenCV 4 REQUIRED )
# Add header file
include_directories(include ${OpenCV_INCLUDE_DIRS} )
add_executable(imgproc main.cpp)
我发现替换这些包括:
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
与:
#include <opencv2/opencv.hpp>
然后一切正常!
经过一番摸索,我终于解决了这个问题。要在 M1 Mac 上使用 openCV 库,您需要包含
-I/opt/homebrew/Cellar/opencv/4.5.5/include/opencv4/ -lopencv_core -lopencv_imgcodecs -lopencv_highgui -L/opt/homebrew/Cellar/opencv/4.5.5/lib/
作为您的 g++ 编译选项。
我在macOS下测试OpenCV成功,参考: https://medium.com/@mfkhao2009/set-up-opencv-development-enrioment-875aa69bd403
您应该通过将此代码添加到
CMakeLists.txt
来将库链接到目标imgproc
add_executable(imgproc main.cpp)
target_link_libraries(imgproc PUBLIC ${OpenCV_LIBS} )
// or in old cmake version:
add_executable(imgproc main.cpp)
target_link_libraries(imgproc ${OpenCV_LIBS} )
我一直在处理同样的问题。我不断收到链接器错误(架构arm64的未定义符号...)。仅供参考,我通过自制程序安装在我的 M1 mac 上,并使用 CLion 进行开发。
解决这个问题的方法是将其添加到 cmake 中指定的 X86_64 中:
set(CMAKE_OSX_ARCHITECTURES x86_64)
我的完整
CMakeLists.txt
:
cmake_minimum_required(VERSION 3.9)
set(CMAKE_OSX_ARCHITECTURES x86_64)
project(opencvtest)
set(CMAKE_CXX_STANDARD 23)
find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})
add_executable(opencvtest main.cpp)
target_link_libraries(opencvtest ${OpenCV_LIBS})