视觉SLAM实践入门——(5)OpenCV之基本用法

本文详细介绍了如何在Ubuntu系统上安装OpenCV 3.1.0,并通过C++示例展示了读取、处理图像的基本步骤,包括图像信息获取、遍历和显示。

安装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})

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值