Dlib学习笔记:解决dlib array2d转 OpenCV Mat时颜色失真

来源:互联网 发布:最新php环境搭建 编辑:程序博客网 时间:2024/05/22 05:10

Dlib学习笔记:解决dlib array2d转 OpenCV Mat时颜色失真

尊重原创,转载请注明出处】 http://blog.csdn.net/guyuealian/article/details/77482549
   在Dlib库中图像存储是使用array2d类型,而在OpenCV是使用Mat类型,Dlib中提供了#include <dlib/opencv.h>,可实现dlib array2d与 OpenCV Mat的互转。其中toMat对象可将dlib的图像转为OpenCV的Mat类型,而cv_image对象可将OpenCV的Mat类型转为dlib类型的图像。详见官网:http://dlib.net/imaging.html#rgb_pixel 
    (1)dlib载入灰度图像:
dlib::array2d<unsigned char> img_gray;//使用dlib载入灰度图像  dlib::load_image(img_gray, "test_image.jpg"); 
将dlib的灰度图像转为OpenCV Mat的图像
#include <dlib/opencv.h>  #include <opencv2/opencv.hpp>  cv::Mat img = dlib::toMat(img_gray);//灰度图 
    若要将OpenCV Mat转为dlib,可以这样:
#include <dlib/opencv.h>  #include <opencv2/opencv.hpp>  cv::Mat img = cv::imread("test_image.jpg")  dlib::cv_image<unsigned char> dlib_img(img); // only stores pointer, no deep copy  
    (2)使用dlib载入彩色的RGB图像
dlib::array2d<dlib::rgb_pixel> img_rgb;//使用dlib载入彩色的RGB图像  dlib::load_image(img_rgb, "test_image.jpg");  
将dlib彩色图像转为OpenCV Mat类型的图像:
cv::Mat img = dlib::toMat(img_rgb);
转换后,图像显示会出现严重的颜色失真现象,如下图所示,左图是dlib显示的img_rgb图像,右图是OpenCV显示的img图像
    后来官网查了一下,原来dlib有多种图像类型;http://dlib.net/imaging.html 
  • RGB
      There are two RGB pixel types in dlib, rgb_pixel and bgr_pixel. Each defines a 24bit RGB pixel type. The bgr_pixel is identical to rgb_pixel except that it lays the color channels down in memory in BGR order rather than RGB order and is therefore useful for interfacing with other image processing tools which expect this format (e.g. OpenCV).
  • RGB Alpha
      The rgb_alpha_pixel is an 8bit per channel RGB pixel with an 8bit alpha channel.
  • HSI
      The hsi_pixel is a 24bit pixel which represents a point in the Hue Saturation Intensity (HSI) color space.
  • LAB
      The lab_pixel is a 24bit pixel which represents a point in the CIELab color space.
  • Grayscale
      Any built in scalar type may be used as a grayscale pixel type. For example, unsigned char, int, double, etc.
而RGB类型有 rgb_pixel和bgr_pixel两种,细看文档,才知道,dlib要想不失真的转到OpenCV中,应该使用bgr_pixel,原因很简单,OpenCV中的颜色也是以“B,G,R”通道顺序排列的。
dlib::array2d<dlib::bgr_pixel> img_bgr;//使用dlib载入彩色的RGB图像    dlib::load_image(img_bgr, "test_image.jpg"); cv::Mat img = dlib::toMat(img_bgr);