Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

For most image file types, cv::imread returns an image whose channel precision is 8-bit unsigned (CV_8UC1, CV_8UC3, CV_8UC4).

Most image file types simply do not support the storage of floating-point data. It is either converted into 8-bit unsigned values, or it does something else unexpected.

Before giving a suggestion on how to persist (save/load) matrices of floating point values, please edit your question to provide more background information.

For most image file types, cv::imread returns an image whose channel precision is 8-bit unsigned (CV_8UC1, CV_8UC3, CV_8UC4).

Most image file types simply do not support the storage of floating-point data. It is either converted into 8-bit unsigned values, or it does something else unexpected.

Before giving a suggestion on how to persist (save/load) matrices of floating point values, please edit your question to provide more background information.

As berak says in the comment, there is a fundamental difference between "compile-time type" and "runtime type", in a statically-typed language such as C++. There are certain limitations we must live with C++, and there are many techniques for overcoming or working around them. However it will be too long to cover here.

To correctly check and convert type, use the following snippet:

cv::Mat matInputUnknownType = cv::imread("...");
int matType = matInputUnknownType.type();
if (matType == CV_8UC1)
{
    cv::Mat1b mat = matInputUnknownType;
   //  use it
}
if (matType == CV_8UC3)
{
    cv::Mat3b mat = matInputUnknownType;
   //  use it
}
if (matType == CV_8UC1)
{
    cv::Mat4b mat = matInputUnknownType;
   //  use it
}

If your code always expect CV_8UC3, you can use the following:

cv::Mat3b matInput;
cv::Mat matTemp = cv::imread("...");
switch (matTemp.type())
{
case CV_8UC1: cv::cvtColor(matTemp, matInput, CV_GRAY2BGR); break;
case CV_8UC3: matInput = matTemp; break;
case CV_8UC4: ...
default: dance();
}