Mat創建
1、使用Mat構造函數
Mat test(2,2,CV_8UC3,Scalar(0,0,255));
2、使用Mat構造函數2
int sizes[3] = {2,2,2};
Mat test(3,sizes,CV_8UC3,Scalar::all(0));
3、爲已存在的IplImage指針創建信息頭
IplImage* img = cvLoadImage("1.jpg",1);
Mat test(img);
4、利用create函數
Mat test;
test.create(4,4,CV_8UC2);
5、採用Matlab形式的初始化方式
(1)Mat me = Mat::eye(4,4,CV_64F);
(2)Mat mo = Mat::ones(2,2,CV_32F);
(3)Mat mz = Mat::zeros(3,3,CV_8UC1);
注:元素類型,即CV_[位數][帶符號與否][類型前綴]C[通道數]
1.at
image.at<uchar>(i, j)
來獲取或改變該點的值,而RGB通道的則可以使用:
image.at<Vec3b>(i, j)[0]
image.at<Vec3b>(i, j)[1]
image.at<Vec3b>(i, j)[2]
來分別獲取B、G、R三個通道的對應的值。下邊的代碼實現對圖像加椒鹽噪聲:
#include<opencv2\opencv.hpp>
using namespace cv;
using namespace std;
void salt_noise(Mat image, int time)
{
for (int k = 0; k < time; k++)//time is the number of the noise you add
{
int i = rand() % image.rows;
int j = rand() % image.cols;
if (image.channels() == 1)//single channel
{
image.at<uchar>(i, j) = rand() % 255;
}
else if (image.channels() == 3)//RGB channel
{
image.at<Vec3b>(i, j)[0] = rand() % 255;
image.at<Vec3b>(i, j)[1] = rand() % 255;
image.at<Vec3b>(i, j)[2] = rand() % 255;
}
}
}
int main(void)
{
Mat image = imread("..\\lena.bmp", 0);
if (image.empty())
{
cout << "load image error" << endl;
return -1;
}
salt_noise(image, 3000);
namedWindow("image", 1);
imshow("image", image);
waitKey();
return 0;
}
不過貌似用at取值或改變值來做比較耗時,當然我們還可以使用Mat的模板子類Mat_<T>,,對於單通道的具體使用:
Mat_<uchar> img = image;
img(i, j) = rand() % 255;
對於RGB通道的使用:
Mat_<Vec3b> img = image;
img(i, j)[0] = rand() % 255;
img(i, j)[1] = rand() % 255;
mg(i, j)[2] = rand() % 255;
還可以用指針的方法遍歷每一像素:(耗時較小)
void colorReduce(Mat image, int div = 64)
{
int nrow = image.rows;
int ncol = image.cols*image.channels();
for (int i = 0; i < nrow; i++)
{
uchar* data = image.ptr<uchar>(i);//get the address of row i;
for (int j = 0; j < ncol; j++)
{
data[i] = (data[i] / div)*div ;
}
}
}
2 Mat::zeros()
返回指定的大小和類型的零數組,即創建數組。
C++: static MatExpr Mat::zeros(int rows, int cols, int type)
C++: static MatExpr Mat::zeros(Size size, int type)
C++: static MatExpr Mat::zeros(int ndims, const int* sizes, int type)
參數
ndims – 數組的維數。
rows–行數。
cols –列數。
size–替代矩陣大小規格Size(cols, rows)的方法。
sizes– 指定數組的形狀的整數數組。
type– 創建的矩陣的類型。
該方法返回一個 Matlab 式的零數組初始值設定項。它可以用於快速形成一個常數數組作爲函數參數,作爲矩陣的表達式或矩陣初始值設定項的一部分。
Mat A;
A = Mat::zeros (3,3,CV_32F);
在上面的示例中,只要A不是 3 x 3浮點矩陣它就會被分配新的矩陣,否則爲現有的矩陣 A填充零。