2

I have a cv::Mat img which I am trying to convert to CV_8UC3 using this:

cv::cvtColor(img, dst, cv::COLOR_GRAY2RGB);

It is throwing this error:

 Exception: OpenCV(4.2.0) external/opencv/modules/imgproc/src/color.simd_helpers.hpp:92: error: 
(-2:Unspecified error) in function 'cv::impl::(anonymous namespace)::CvtHelper<cv::impl::(anonymous namespace)::Set<1, -1, -1>, 
cv::impl::(anonymous namespace)::Set<3, 4, -1>, cv::impl::(anonymous namespace)::Set<0, 2, 5>, cv::impl::(anonymous namespace)::NONE>::CvtHelper(cv::InputArray, cv::OutputArray, int) 
[VScn = cv::impl::(anonymous namespace)::Set<1, -1, -1>, VDcn = cv::impl::(anonymous namespace)::Set<3, 4, -1>, VDepth = cv::impl::(anonymous namespace)::Set<0, 2, 5>, 
sizePolicy = cv::impl::(anonymous namespace)::NONE]'
    Invalid number of channels in input image:
    'VScn::contains(scn)' where 'scn' is 3

Any ideas what this may mean?

alittlebirdy
  • 93
  • 1
  • 7

1 Answers1

4

The error means image is already "color" (meaning it already has 3 channels). OpenCV can't convert it from GRAY to RGB because a gray image only has one color channel.

CV_8UC3 means you have 3 color channels with 8-bit depth. If you really want to make sure you have a CV_8UC3, you can try something like this when making your image:

// create a new 320x240 image
Mat img(Size(320,240),CV_8UC3);

If you share how you are creating img, I could confirm this is the case, but at any rate that is what the error means.

Update

This answer gives some good guidance on debugging your Mat objects. According to the error code, you already have a 3 channel image, so that takes care of the C3 part. The 8U part means it is all 8 bit unsigned binary data, on a scale of 0 to 255. Once you know the output of the script I mentioned above, you can scale it or convert it accordingly.

This answer details how to convert to different bit depths.

Salvatore
  • 10,815
  • 4
  • 31
  • 69
  • Thanks Matthew. The img is created as a result of stitching images together following the opencv detailed stitching algorithm here: https://github.com/opencv/opencv/blob/master/samples/cpp/stitching_detailed.cpp . If I print out `img.type()` it gives me `19` instead of `CV_8UC3` which threw me off. In that case, how can I make sure its type gives me `CV_8UC3` ? – alittlebirdy Apr 09 '20 at 00:09
  • @alittlebirdy I updated my answer. Try what you see there and tell me what you get. – Salvatore Apr 09 '20 at 00:22
  • Matthew, it looks like my image type is `CV_16S`. According to the second link, I can try something like this: `img.convertTo(img, CV_8U, 0.00390625);` and it works perfectly! Thank you so much! – alittlebirdy Apr 09 '20 at 01:00