对于部分初学者,偶尔会想在代码中查看图片的位深度,一般我们会用Mat.type()来获得类型,但是默认输出的是整型数字,不便于理解,可能还需要自己对照宏定义去查看,这里有一段代码可以实现将整型转为宏定义位深度
string Type2String(int type){ string strType; uchar depth = type & CV_MAT_DEPTH_MASK; uchar chans = 1 + (type >> CV_CN_SHIFT); switch (depth) { case CV_8U: strType = "CV_8U"; break; case CV_8S: strType = "CV_8S"; break; case CV_16U: strType = "CV_16U"; break; case CV_16S: strType = "CV_16S"; break; case CV_32S: strType = "CV_32S"; break; case CV_32F: strType = "CV_32F"; break; case CV_64F: strType = "CV_64F"; break; default: strType = "UNKNOWN_TYPE"; break; } strType += "C"; strType += (chans + '0'); return strType;}
比如,使用imread读取图片,如果flags参数不填,默认以彩色模式读取并转为8位,那么类型就是CV_8UC3, 如果flags设置位0,则以灰度模式读取,类型位CV_8UC1。但是,有时候我们会读取一些16位或32位的图片,这时候就需要设置flags参数为 IMREAD_UNCHANGED,这样读取的图片位深度才会被正确显示,如下:
Mat img = imread("1.tif", IMREAD_UNCHANGED);cout <endl;cout <endl;
flags参数其他含义可以参考定义说明查看:
完整代码:
#include#includeusing namespace std;using namespace cv;string Type2String(int type){ string strType; uchar depth = type & CV_MAT_DEPTH_MASK; uchar chans = 1 + (type >> CV_CN_SHIFT); switch (depth) { case CV_8U: strType = "CV_8U"; break; case CV_8S: strType = "CV_8S"; break; case CV_16U: strType = "CV_16U"; break; case CV_16S: strType = "CV_16S"; break; case CV_32S: strType = "CV_32S"; break; case CV_32F: strType = "CV_32F"; break; case CV_64F: strType = "CV_64F"; break; default: strType = "UNKNOWN_TYPE"; break; } strType += "C"; strType += (chans + '0'); return strType;}void main(){ Mat img = imread("1.tif", IMREAD_UNCHANGED); cout << img.type() << endl; cout << Type2String(img.type()) << endl;}