1. 程式人生 > >ImageMagick 的 Image 和 OpenCV 的 cv::Mat 如何轉換

ImageMagick 的 Image 和 OpenCV 的 cv::Mat 如何轉換

參考自: http://blog.csdn.net/revolver/article/details/12851395


僅以 BGR 格式為例:

一、cv::Mat -> Image

Image Mat2Magick(const cv::Mat& img )  
{  
   Image mgk(img.cols, img.rows, "BGR", MagickCore::CharPixel, (char *)img.data);  
   return mgk;  
}  



二、Image -> cv::Mat

void Magick2Mat(Image& magicImage, cv::Mat& img)  
{  
   int width= magicImage.size().width();  
   int height = magicImage.size().height();  
   int size = 3 * width * height;

   uchar* blob= new uchar[size];  
   magicImage.write(0,0, width, height, "BGR", MagickCore::CharPixel, blob);  

   img.create(height, width, CV_8UC3);
   memcpy(img.data, blob, size);  

   delete [] blob;  
} 


三、其他格式

ImageMagick 支援的其他儲存格式

typedef enum
{
  UndefinedPixel,
  CharPixel,
  DoublePixel,
  FloatPixel,
  LongPixel,
  LongLongPixel,
  QuantumPixel,
  ShortPixel
} StorageType;

OpenCV 支援的格式

#define CV_8UC1 CV_MAKETYPE(CV_8U,1)
#define CV_8UC2 CV_MAKETYPE(CV_8U,2)
#define CV_8UC3 CV_MAKETYPE(CV_8U,3)
#define CV_8UC4 CV_MAKETYPE(CV_8U,4)
#define CV_8UC(n) CV_MAKETYPE(CV_8U,(n))

#define CV_8SC1 CV_MAKETYPE(CV_8S,1)
#define CV_8SC2 CV_MAKETYPE(CV_8S,2)
#define CV_8SC3 CV_MAKETYPE(CV_8S,3)
#define CV_8SC4 CV_MAKETYPE(CV_8S,4)
#define CV_8SC(n) CV_MAKETYPE(CV_8S,(n))

#define CV_16UC1 CV_MAKETYPE(CV_16U,1)
#define CV_16UC2 CV_MAKETYPE(CV_16U,2)
#define CV_16UC3 CV_MAKETYPE(CV_16U,3)
#define CV_16UC4 CV_MAKETYPE(CV_16U,4)
#define CV_16UC(n) CV_MAKETYPE(CV_16U,(n))

#define CV_16SC1 CV_MAKETYPE(CV_16S,1)
#define CV_16SC2 CV_MAKETYPE(CV_16S,2)
#define CV_16SC3 CV_MAKETYPE(CV_16S,3)
#define CV_16SC4 CV_MAKETYPE(CV_16S,4)
#define CV_16SC(n) CV_MAKETYPE(CV_16S,(n))

#define CV_32SC1 CV_MAKETYPE(CV_32S,1)
#define CV_32SC2 CV_MAKETYPE(CV_32S,2)
#define CV_32SC3 CV_MAKETYPE(CV_32S,3)
#define CV_32SC4 CV_MAKETYPE(CV_32S,4)
#define CV_32SC(n) CV_MAKETYPE(CV_32S,(n))

#define CV_32FC1 CV_MAKETYPE(CV_32F,1)
#define CV_32FC2 CV_MAKETYPE(CV_32F,2)
#define CV_32FC3 CV_MAKETYPE(CV_32F,3)
#define CV_32FC4 CV_MAKETYPE(CV_32F,4)
#define CV_32FC(n) CV_MAKETYPE(CV_32F,(n))

#define CV_64FC1 CV_MAKETYPE(CV_64F,1)
#define CV_64FC2 CV_MAKETYPE(CV_64F,2)
#define CV_64FC3 CV_MAKETYPE(CV_64F,3)
#define CV_64FC4 CV_MAKETYPE(CV_64F,4)
#define CV_64FC(n) CV_MAKETYPE(CV_64F,(n))


比如 Image 為 單通道的FloatPixel,那麼 cv::Mat 就應該改為 CV_32FC1 與之對應。


四、如何使用

使用方法也十分簡單,直接上程式碼


1) Image -> Mat

cv::Mat img;
Magick2Mat(image, img);
cv::imshow("Magick2Mat", img);
cv::waitKey(0);


2) Mat -> Image

Image test = Mat2Magick(img);
test.write("Mat2Magick.jpg");


PS: 通過檢視 ImageMagick 原始碼(Pixel.c)

ImportImagePixels() 【由 image.cpp 的 ConstituteImage 呼叫】 裡面定義了顏色對映的字串含義

可以是以下的任意組合:

/ *     R = red, G = green, B = blue,
 %      A = alpha (0 is transparent), O = opacity (0 is opaque), C = cyan,
 %      Y = yellow, M = magenta, K = black, I = intensity (for grayscale),
 %      P = pad. */