安装OpenCV
下载链接
https://opencv.org/releases/
选择 OpenCV – 3.1.0 — Sources,下载并解压,得到opencv-3.1.0目录
先安装一些依赖项:
sudo apt install build-essential libgtk2.0-dev libvtk5-dev libjpeg-dev libtiff5-dev libjasper-dev libopenexr-dev libtbb-dev
配置编译安装OpenCV
cd opencv-3.1.0
mkdir build && cd build
cmake ..
make && sudo make install
默认安装后,头文件位于/usr/local/include/opencv4/opencv2,库位于/usr/local/lib
代码
其中图片是slambook2/ch5/imageBasics/ubuntu.png,将图片拷贝到工程根目录。运行执行程序时,进入build目录,输入命令 ./useOpenCV ../ubuntu.png 即可(useOpenCV是执行程序名,../ubuntu.png是图片的相对路径)
#include <iostream>
#include <chrono>
using namespace std;
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace chrono;
int main(int argc, char **argv) {
//从命令行(第一个参数)读出图像文件名
Mat image = imread(argv[1]);
//判断图像文件是否正确读取
if(image.data == nullptr)
{
cerr << "文件" << argv[1] << "不存在" << endl;
return 0;
}
//输出基本信息
cout << "图像宽*高*通道数为:" << image.cols << "*" << image.rows << "*" << image.channels() << endl;
//显示图像
imshow("image", image);
//等待按键输入
waitKey(0);
//判断image类型
if(image.type() != CV_8UC1 && image .type() != CV_8UC3)
{
cout << "请输入灰度图或彩色图" << endl;
return 0;
}
//遍历图像,这种遍历方式也可以用于随机像素访问
steady_clock::time_point t1 = steady_clock::now();
for(size_t y = 0; y < image.rows; y++)
{
unsigned char *row_ptr = image.ptr<unsigned char>(y); //指向第y行
//ptr<>(y),取行指针;ptr<>(y)[x]取元素指针(列)指针
for(size_t x = 0; x < image.cols; x++)
{
unsigned char *data_ptr = &row_ptr[x*image.channels()]; //指向访问数据
for(int c = 0; c != image.channels(); c++)
unsigned char data = data_ptr[c]; //第c个通道的值
}
}
steady_clock::time_point t2 = steady_clock::now();
duration<double> time_used = duration_cast<duration<double>>(t2 - t1); //cast是显示类型转换
cout << "遍历图像用时:" << time_used.count() << "秒" << endl;
//cv::Mat的拷贝
Mat image_another = image; //直接赋值不会拷贝数据,修改image_another却会影响原图像,大概是用两个指针指向同一块缓存?
image_another(Rect(0, 0, 100, 100)).setTo(0); //将左上角100*100矩阵置0
imshow("image", image);
waitKey(0);
//销毁窗口,回收内存
destroyAllWindows();
return 0;
}
在CMakeLists.txt中加入
add_definitions(-std=c++11)
find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})
target_link_libraries(useopencv ${OpenCV_LIBS})
本文详细介绍了如何在Ubuntu系统上安装OpenCV 3.1.0,并通过C++示例展示了读取、处理图像的基本步骤,包括图像信息获取、遍历和显示。
122

被折叠的 条评论
为什么被折叠?



