opencv-003-图像对象(Mat)创建与赋值

知识点

  1. C++中Mat对象与创建
  2. Python中Numpy数组对象

代码(c++,python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main(){
Mat src = imread("../images/liuyifei_1.png");

// 通过克隆或复制创建图像对象,m1和src指向不同内存块
Mat m1 = src.clone();
Mat m2;
src.copyTo(m2);

// 赋值法,m3和src指向同一内存块
Mat m3 = src;

// 创建空白图像
Mat m4 = Mat::zeros(src.size(),src.type());
Mat m5 = Mat::zeros(Size(512,512),CV_8UC3);
Mat m6 = Mat::ones(Size(512,512),CV_8UC3);

// kernel: [0, -1, 0
// -1, 5, -1
// 0, -1, 0]
Mat kernel = (Mat_<char>(3,3)<<0,-1,0,-1,5,-1,0,-1,0);

waitKey(0);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import cv2 as cv
import numpy as np

src = cv.imread("../images/liuyifei_1.png")
cv.namedWindow("input", cv.WINDOW_AUTOSIZE)
cv.imshow("input", src)

# 克隆图像
m1 = np.copy(src)

# 赋值
m2 = src
src[100:200,200:300,:] = 255 # 第三维代表图像通道
cv.imshow("m2",m2)

m3 = np.zeros(src.shape, src.dtype)
cv.imshow("m3", m3)

m4 = np.zeros([512,512], np.uint8)
# m4[:,:] =127 try to give gray value 127
cv.imshow("m4", m4)

m5 = np.ones(shape=[512,512,3], dtype=np.uint8)
m5[:,:,0] = 255
cv.imshow("m5", m5)

cv.waitKey(0)
cv.destroyAllWindows()

代码地址

github