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 <opencv2/core.hpp>
#include <iostream>
using namespace cv;
int main()
{
Mat a;
std::cout << a;
return 0;
}
output:
[]
- Initialize with type and size (row, col) (1):
#include <opencv2/core.hpp>
#include <iostream>
using namespace cv;
int main()
{
Mat a = Mat_<int>(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 <opencv2/core.hpp>
#include <iostream>
using namespace cv;
int main()
{
Mat a(8, 6, CV_8UC3);
std::cout << a;
return 0;
}
output:
- Initialize with
Size
struct
#include <opencv2/core.hpp>
#include <iostream>
#include <opencv2/core/hal/interface.h>
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 <opencv2/core.hpp>
#include <iostream>
#include <opencv2/core/hal/interface.h>
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 <iostream>
#include <opencv2/core.hpp>
#include <opencv2/core/hal/interface.h>
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 <opencv2/core.hpp>
#include <iostream>
#include <opencv2/core/hal/interface.h>
using namespace cv;
int main()
{
Size size(3, 4);
Mat a(size, CV_8UC1);
Mat b(a);
a.at<unsigned int>(0, 0) = 1;
std::cout << a << std::endl;
std::cout << b;
return 0;
}
output:
Deep copy of Mat
object
#include <opencv2/core.hpp>
#include <iostream>
#include <opencv2/core/hal/interface.h>
using namespace cv;
int main()
{
Size size(3, 4);
Mat a(size, CV_8UC1);
Mat b = a.clone();
a.at<unsigned int>(0, 0) = 1;
std::cout << a << std::endl;
std::cout << b;
return 0;
}
output: