OpenCV图像从RGB转换为灰度异常

时间:2014-04-23 22:52:11

标签: opencv

当我尝试将RGB图像转换为灰度时,我得到一个奇怪的异常(异常:在内存位置0x002EB6CC处的cv :: Exception)。有人能帮助我吗?

  const cv::Mat img1 = cv::imread(filename, 0)
  cv::Mat gs_rgb(img1.size(), CV_8UC1);
  cv::cvtColor(img1, gs_rgb, CV_RGB2GRAY);

1 个答案:

答案 0 :(得分:5)

您正在将图像加载为灰度,并尝试再次将灰度转换为灰度。

该行

  const cv::Mat img1 = cv::imread(filename, 0)

将加载图片

其中第二个参数

=0->CV_LOAD_IMAGE_GRAYSCALE->load gray scale
=1->CV_LOAD_IMAGE_COLOR->load color
<0->CV_LOAD_IMAGE_ANYDEPTH->Return the loaded image as is (with alpha channel).

因此,要么将图像加载为灰度,请将其用作

  const cv::Mat img1 = cv::imread(filename, 0)//load gray

或者将其加载为颜色,然后转换为灰度,如

  const cv::Mat img1 = cv::imread(filename, 1);//load color
  Mat gray;//no need of allocation, will allocate automatically.
  cv::cvtColor(img1,gray, CV_BGR2GRAY);//opencv default color order is BGR

imread documentation中查看更多信息。