OpenCV官方文档中三通道图片像素生成是这样实现的
Mat M(2,2,CV_8UC3,Scalar(0,0,255));
//其中“2,2”表示Rows和Cols各为2;
CV_8UC3表示M矩阵对应的参数类型是Unsigned char 8bits,3通道;
标量Scalar(0,0,255)表示每个像素所对应的像素值
补充:
- 8-bit unsigned integer (uchar)
- 8-bit signed integer (schar)
- 16-bit unsigned integer (ushort)
- 16-bit signed integer (short)
- 32-bit signed integer (int)
- 32-bit floating-point number (float)
- 64-bit floating-point number (double)
- a tuple of several elements where all elements have the same type
(one of the above). An array whose elements are such tuples, are
called multi-channel arrays, as opposite to the single-channel
arrays, whose elements are scalar values. The maximum possible number
of channels is defined by the CV_CN_MAX constant, which is currently
set to 512.
对于以上这些基本类型, 有以下应用枚举:
enum { CV_8U=0, CV_8S=1, CV_16U=2, CV_16S=3, CV_32S=4, CV_32F=5, CV_64F=6 };
当然也可以自定义Mat的数据类型
- Example:
目的:生成一个2x3x5的矩阵,数据类型为double,并进行赋值
//自定义数据类型
typedef cv::Vec<double, 5> Vec5d;
//生成一个2x3x5的Mat,数据为double型
Mat M = cv::Mat::zeros(2, 3, CV_64FC(5));
std::cout << "channel = " << M.channels() << endl;//输出为5
for (int i = 0; i < M.rows; i++)
{
for (int j = 0; j < M.cols; j++)
{
for (int c = 0; c <M.channels(); c++)
{
//给M的每一个元素赋值
M.at<Vec5d>(i, j)[c] = c*0.01;
}
}
}
cout <<M << endl;//输出矩阵
代码运行结果: