1. 程式人生 > >Dlib學習筆記:解決dlib array2d轉 OpenCV Mat時顏色失真

Dlib學習筆記:解決dlib array2d轉 OpenCV Mat時顏色失真

Dlib學習筆記:解決dlib array2d轉 OpenCV Mat時顏色失真

 

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的影象

 
  1. #include <dlib/opencv.h>

  2. #include <opencv2/opencv.hpp>

  3. cv::Mat img = dlib::toMat(img_gray);//灰度圖

  若要將OpenCV Mat轉為dlib,可以這樣:

    若要將OpenCV Mat轉為dlib,可以這樣:
 
  1. #include <dlib/opencv.h>

  2. #include <opencv2/opencv.hpp>

  3. cv::Mat img = cv::imread("test_image.jpg")

  4. dlib::cv_image<unsigned char> dlib_img(img); // only stores pointer, no deep copy

 (2)使用dlib載入彩色的RGB影象:

 
  1. dlib::array2d<dlib::rgb_pixel> img_rgb;//使用dlib載入彩色的RGB影象

  2. 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”通道順序排列的。

 
  1. dlib::array2d<dlib::bgr_pixel> img_bgr;//使用dlib載入彩色的RGB影象

  2. dlib::load_image(img_bgr, "test_image.jpg");

  3. cv::Mat img = dlib::toMat(img_bgr);