opencv-003-图像对象(Mat)创建与赋值 发表于 2019-03-21 | 分类于 opencv 知识点 C++中Mat对象与创建 Python中Numpy数组对象 代码(c++,python)123456789101112131415161718192021222324252627282930#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;} 12345678910111213141516171819202122232425262728import cv2 as cvimport numpy as npsrc = cv.imread("../images/liuyifei_1.png")cv.namedWindow("input", cv.WINDOW_AUTOSIZE)cv.imshow("input", src)# 克隆图像m1 = np.copy(src)# 赋值m2 = srcsrc[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 127cv.imshow("m4", m4)m5 = np.ones(shape=[512,512,3], dtype=np.uint8)m5[:,:,0] = 255cv.imshow("m5", m5)cv.waitKey(0)cv.destroyAllWindows() 代码地址github