OpenCV加载图片显示对应类型(位深度)方法

时间:2022-07-22
本文章向大家介绍OpenCV加载图片显示对应类型(位深度)方法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

对于部分初学者,偶尔会想在代码中查看图片的位深度,一般我们会用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 << img.type() << endl;
cout << Type2String(img.type()) << endl;

flags参数其他含义可以参考定义说明查看:

完整代码:

#include<iostream>
#include<opencv2/opencv.hpp>

using 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;
}