1.OpenCV中图像对象创建与赋值
- 读取:imread、创建(如Mat::zeros(size,typea))
- =
- copy和clone函数
2. C++中Mat对象与创建
- = :只是复制了头,实际数据指向同一块内存
- clone和copy:头部和数据都新开辟一块内存
C++ Mat的常用
CV_8UC3理解: https://www.chengxulvtu.com/opencv-mat/
8U表示每个元素由8位(一个char)构成,C3表示3通道:每个像素由三个元素构成
Python常用:
src[:,:,:]中前两个分别是高和宽的区域范围,对应的通道数
2.示例
Python
1 import cv2 as cv 2 import numpy as np 3 4 5 src = cv.imread("D:/vcprojects/images/test.png") 6 cv.namedWindow("input", cv.WINDOW_AUTOSIZE) 7 cv.imshow("input", src) 8 9 10 # 克隆图像 11 m1 = np.copy(src) 12 13 14 # 赋值 15 m2 = src 16 src[100:200,200:300,:] = 255 17 cv.imshow("m2",m2) 18 19 20 m3 = np.zeros(src.shape, src.dtype) 21 cv.imshow("m3", m3) 22 23 24 m4 = np.zeros([512,512], np.uint8) 25 # m4[:,:] =127 try to give gray value 127 26 cv.imshow("m4", m4) 27 28 29 m5 = np.ones(shape=[512,512,3], dtype=np.uint8) 30 m5[:,:,0] = 255 31 cv.imshow("m5", m5) 32 33 34 cv.waitKey(0) 35 cv.destroyAllWindows()
C++
1 #include <opencv2/opencv.hpp> 2 #include <iostream> 3 4 using namespace cv; 5 using namespace std; 6 7 int main(int artc, char** argv) { 8 Mat src = imread("D:/vcprojects/images/test.png"); 9 if (src.empty()) { 10 printf("could not load image... "); 11 return -1; 12 } 13 namedWindow("input", CV_WINDOW_AUTOSIZE); 14 imshow("input", src); 15 16 // 创建方法 - 克隆 17 Mat m1 = src.clone(); 18 19 // 复制 20 Mat m2; 21 src.copyTo(m2); 22 23 // 赋值法 24 Mat m3 = src; 25 26 // 创建空白图像 27 Mat m4 = Mat::zeros(src.size(), src.type()); 28 Mat m5 = Mat::zeros(Size(512, 512), CV_8UC3); 29 Mat m6 = Mat::ones(Size(512, 512), CV_8UC3); 30 31 Mat kernel = (Mat_<char>(3, 3) << 0, -1, 0, 32 -1, 5, -1, 33 0, -1, 0); 34 35 waitKey(0); 36 return 0; 37 }