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

How to convert CV_8UC1 to normal int type?

本文关键字:int 类型 转换 8UC1 CV      更新时间:2023-10-16

我在理解opencv类型时遇到了问题。我有矩阵在CV_8UC1类型,但我怎么能读取矩阵元素的值?

我知道我必须使用at方法,然后通过<here>我的类型,但CV_8UC1是什么类型?8位无符号位单通道不能告诉我太多。

我可以这样做吗?Unsigned int a = mat->at(0,0);

来自OpenCV参考手册:

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

所以它只是单通道8位灰度值0到255

下面是几个例子:

  • P。stackoverflow有时不允许使用><所以我将使用}和{来代替>

.

// 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 depthn");
     break;
case sizeof(double):
     printf("This matrix has 64 bit depthn");
     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