Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Is there an OpenCV idiom for converting arbitrary input images to a desired format?

Setup: Suppose I want to read images from arbitrary cameras or input files and don't know ahead of time if the images will be greyscale, color, 8 bits/pixel, 16 bits/pixel, etc...

I used to think that I could call get(CV_CAP_FRAME_FORMAT) to determine the fixed frame format for the images returned by my VideoCapture() object, but I have since learned that I cannot count on that feature being implemented, even for fixed format .bmp files.

Is there some common OpenCV idiom for determining the input format of a camera (or file) and for dynamically transforming that to the format required by downstream processing?

For example, suppose I have a single channel grayscale image (CV_8UC1) that I need to convert to RGB because my downstream algorithm assumes/requires RGB (or vice versa). I can call cvtColor() to do the conversion, but I must not do that if the input data stream is already an RGB stream. How do OpenCV experts typically handle this situation?

I could do something like this:

while (true) {
  cap >> image;
  switch(image.type())
  case CV_8UC3:
    // This is what my downstream algorithm expects
    // (Actually, I can't tell if the image is in RGB or BGR format
    // here.  That's probably yet another problem all together).
    break;

  case CV_8UC1:
    Mat converted;
    cv.cvtColor(image, converted, CV_GRAY2RGB);
    image = converted;
    break;

  ...

Thanks.

--wpd