如何将CV_8UC1转换为普通int类型?

时间:2011-07-17 15:55:38

标签: c++ opencv

我在理解opencv类型方面遇到了问题。我在CV_8UC1类型中有矩阵但是如何读取矩阵中元素的值?

我知道我必须在方法中使用然后传递<here>我的类型,但CV_8UC1是什么类型的? 8个无符号位单通道并没有告诉我多少。

我可以这样做: unsigned int a = mat-&gt; at(0,0);

2 个答案:

答案 0 :(得分:1)

来自OpenCV参考手册:

CV_8UC1 – unsigned 8-bit single-channel data; can be used for grayscale image or binary image – mask.

所以它只是单通道8位灰度,值为0..255。

答案 1 :(得分:1)

以下是一些例子:

  • P.s stackoverflow有时不允许使用&gt;&lt;因此我将使用}和{而不是

// Char single channel matrix
Mat M1 = mat::ones(3,5,CV_8UC1);
int Val = M1{unsigned char}.at(2,3);

// int 16 matrix with 3 channels (like RGB pixel)
Mat M2 = mat::ones(3,5,CV_16UC(3));
__int16* Pix = &M2.at<__int16>(2,3);
Val = Pix[0] + Pix[1] + Pix[2];

// Example of how to find the size of each element in matrix
switch ( (M.dataend-M.datastart) / (M.cols*M.rows*M.channels())){
case sizeof(char):
     printf("This matrix has 8 bit depth\n");
     break;
case sizeof(double):
     printf("This matrix has 64 bit depth\n");
     break;
}

//Example of how to build dynamically a Matrix with desired depth
int inline CV_BUILD_MATRIX_TYPE(int elementSize, int nChannels){
    // Determine type of the matrix 
    switch (elementSize){
    case sizeof(char):
         return CV_8UC(nChannels);
         break;
    case (2*sizeof(char)):
         return CV_16UC(nChannels);
         break;
    case sizeof(float):
         return CV_32FC(nChannels);
         break;
    case sizeof(double):
         return CV_64FC(nChannels);
         break;
    }
    return -1;
}

Mat M = Mat::zeros(2,3,CV_BUILD_MATRIX_TYPE(4,2)); 
// builds matrix with 2 channels where each channel has depth of 4 bytes (float or __int32). As you wish