装了双系统,所以想把工作尽量在Ubuntu下面完成。以前在Windows下面使用opencv,现在想在Ubuntu下用。
编写一个例子test.cpp:简单的显示图片
#include
#include
using namespace cv;
int main( int argc, char** argv )
{
Mat image;
image = imread("lena.jpeg");
namedWindow( "Display Image", CV_WINDOW_AUTOSIZE );
imshow( "Display Image", image );
waitKey(0);
return 0;
}
编写CMakeLists.txt文件
cmake_minimum_required(VERSION 2.8)
project( test )
find_package( OpenCV REQUIRED )
add_executable( test test.cpp )
target_link_libraries( test ${OpenCV_LIBS} )
cmake .
make
./test.cpp
如果一切顺利当然会显示图片,但事情总不会一帆风顺。。。
到这一步出现了错误如下所示:
CMake Error at CMakeLists.txt:6 (find_package):
Found package configuration file:
/home/user/opencv-2.4.13/cmake/OpenCVConfig.cmake
but it set OpenCV_FOUND to FALSE so package "OpenCV" is considered to be
NOT FOUND.
set(OpenCV_FOUND 1)
这样就解决了。
在这一步还有可能出现一个问题
CMake Error: Unable to open check cache file for write. /home/user/test/CMakeFiles/cmake.check_cache
这里需要root权限去执行cmake .命令。第二步输入如下命令:
sudo cmake .
根据提示输入密码就成功了
但老天总不会这么轻易放过我,输入第二条指令后又出错了。
test.o:在函数‘main’中:
test.cpp:(.text.startup+0xc):对‘cvLoadImage’未定义的引用
test.cpp:(.text.startup+0x23):对‘cvNamedWindow’未定义的引用
test.cpp:(.text.startup+0x30):对‘cvShowImage’未定义的引用
test.cpp:(.text.startup+0x37):对‘cvWaitKey’未定义的引用
test.cpp:(.text.startup+0x41):对‘cvDestroyWindow’未定义的引用
collect2: error: ld returned 1 exit status
解决方法:在CMakeLists.txt修改这一句find_package(OpenCV [版本号] REQUIRED)
cmake_minimum_required(VERSION 2.8)
project( hello )
find_package( OpenCV 2.4.13 REQUIRED ) #修改这一句啊
add_executable( hello hello.cpp )
target_link_libraries( hello ${OpenCV_LIBS} )
到此就全部解决了
我把这个代码又放到Kdevelop里面跑了一遍,但是出现了如下错误:
OpenCV Error: Assertion failed (size.width>0 && size.height>0) in imshow, file /home/user/opencv-2.4.13/modules/highgui/src/window.cpp, line 261
terminate called after throwing an instance of 'cv::Exception'
what(): /home/user/opencv-2.4.13/modules/highgui/src/window.cpp:261: error: (-215) size.width>0 && size.height>0 in function imshow
解决方法:在代码中,添加放置图片的完整路径
#include
#include
using namespace cv;
int main( int argc, char** argv )
{
Mat image;
image = imread("/home/user/code/test/lena.jpeg"); //这个地方根据你自己放置图片的路径来写
namedWindow( "Display Image", CV_WINDOW_AUTOSIZE );
imshow( "Display Image", image );
waitKey(0);
return 0;
}