Opencv_Mat

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

Mat类中的at方法对于获取图像矩阵某点的RGB值或者改变某点的值很方便,对于单通道的图像,则可以使用:

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填充零。


猜你喜欢

转载自blog.csdn.net/w614171629/article/details/80973199