OpenCV 学习笔记 Chapter 2 Part I

OpenCV 学习笔记 Chapter 2 Part I,第1张

OpenCV 学习笔记 Chapter 2 Part I OpenCV 学习笔记 Chapter 2 Part I

教材:冯振、郭延宁、吕跃勇·《OpenCV4快速入门

Compile with cmake

In case to compile mat.cpp, write CMakeLists.txt :

cmake_minimum_required(VERSION 2.8)
project( mat )
find_package( OpenCV REQUIRED )
include_directories( ${OpenCV_INCLUDE_DIRS} )
add_executable( mat mat.cpp )
target_link_libraries( mat ${OpenCV_LIBS} )

Then generate Makefile and make:

cmake .
make
Ways to initialize Mat object
  • Initialize a header (pointer) to Mat object:
#include 
#include 

using namespace cv;

int main()
{
    Mat a;
    std::cout << a;
    return 0;
}

output:

[]
  • Initialize with type and size (row, col) (1):
#include 
#include 

using namespace cv;

int main()
{
    Mat a = Mat_(3, 4);
    std::cout << a;
    return 0;
}

output:

[0, 0, 0, 0;                                                                                                                                                                         
 0, 0, 0, 0;                                                                                                                                                                         
 0, 0, 0, 0]
  • Initialize with type and size (2):
#include 
#include 

using namespace cv;

int main()
{
    Mat a(8, 6, CV_8UC3);
    std::cout << a;
    return 0;
}

output:

  • Initialize with Size struct
#include 
#include 
#include 

using namespace cv;

int main()
{
    Size size(3, 4);
    Mat a(size, CV_8UC3);
    std::cout << a;
    return 0;
}

output:

  • Initialize with specific value / mode
#include 
#include 
#include 

using namespace cv;

int main()
{
    Mat a = Mat::ones(3, 2, CV_8U);
    std::cout << a;
    return 0;
}

output:

Similar to numpy, there are

Mat::ones
Mat::zeros
...
  • Initialize with values from array
#include 
#include 
#include 

using namespace cv;

int main() {
    float arr[8];
    for (int i = 0; i < 8; i++) {
        arr[i] = float(i) / 10;
    }

    Mat a(2, 3, CV_32F, arr);
    Mat b(3, 4, CV_32F, arr);
    std::cout << a << std::endl << b;
    return 0;
}

output :

Shallow copy of Mat object
#include 
#include 
#include 

using namespace cv;

int main()
{
    Size size(3, 4);
    Mat a(size, CV_8UC1);
    Mat b(a);
    a.at(0, 0) = 1;
    std::cout << a << std::endl;
    std::cout << b;
    return 0;
}

output:

Deep copy of Mat object
#include 
#include 
#include 

using namespace cv;

int main()
{
    Size size(3, 4);
    Mat a(size, CV_8UC1);
    Mat b = a.clone();
    a.at(0, 0) = 1;
    std::cout << a << std::endl;
    std::cout << b;
    return 0;
}

output:

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5689854.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存