2016年3月15日 星期二

Color Conversion using OpenCV

Color Conversion using OpenCV

注意OpenCV讀取影像的影像格式是BGR而不是RGB,所以後續不管是要使用OpenCV提供的API轉換色彩空間或者自行取值運算都要特別注意。以下我們會提供RGB與YCrCb、HSV、HSL、CIE-Lab、XYZ等色彩轉換的公是與方法。

cv::Mat srcImg = cv::imread("lena.jpg", CV_LOAD_IMAGE_COLOR);

//BGR to Gray Color Space
cv::Mat bgr2grayImg;
cv::cvtColor(srcImg, bgr2grayImg, cv::COLOR_BGR2GRAY);

//BGR to HSV Color Space
cv::Mat bgr2hsvImg, hsv2bgrImg;
cv::cvtColor(srcImg, bgr2hsvImg, cv::COLOR_BGR2HSV);

更多的Sample Code請參考Github

cv::imread(const string& filename, int flags=1 )

  • CV_LOAD_IMAGE_UNCHANGED (<0) loads the image as is (including the alpha channel if present)
  • CV_LOAD_IMAGE_GRAYSCALE ( 0) loads the image as an intensity one
  • CV_LOAD_IMAGE_COLOR (>0) loads the image in the BGR format

cv::cvtColor(InputArray src, OutputArray dst, int code, int dstCn=0 )

  • src 來源影像(8-bit unsigned, 16-bit unsigned ( CV_16UC… ), or single-precision floating-point.)
  • dst 輸出影像(與來源影像同格式)
  • code 欲轉換的色彩空間(參考以下常用的色彩轉換)

常用的色彩轉換

  • COLOR_BGR2RGB
  • COLOR_RGB2BGR
  • COLOR_BGR2GRAY (convert between RGB to grayscale)
  • COLOR_BGR2XYZ (convert BGR to CIE XYZ)
  • COLOR_XYZ2BGR
  • COLOR_BGR2YCrCb (convert BGR to luma-chroma)
  • COLOR_YCrCb2BGR
  • COLOR_BGR2HSV (convert BGR to HSV)
  • COLOR_HSV2BGR
  • COLOR_BGR2Lab (convert BGR to CIE Lab)
  • COLOR_Lab2BGR
  • COLOR_BGR2HLS (convert BGR to HLS)
  • COLOR_HLS2BGR

色彩轉換公式

RGB <–> GRAY

RGB <–> CIE XYZ

RGB <–> YCrCb

RGB <–> HSV

RGB <–> HLS

RGB <–> CIE L*a*b*

更多OpenCV文章請參考:OpenCV Tutorial (學習筆記)

0 意見:

張貼留言