49

How do I convert a cv::Mat of type CV_32FC1 to the type CV_64FC1 (equivalent to a change from float to double)?

I am opening a Matrix that was saved as XML (cvSave) but as a float. This means that the field <dt> has the value f in the file. I need to change it to d to open it. But I'd rather not do this, instead I'd like to open it directly as a Matrix with elements of type double, or convert it later from float to double.

Below is my code for opening the file.

/** Load cv::Mat from XML file. 
 */
cv::Mat loadMat(const std::string filename)
{
    cv::Mat result;
    cv::FileStorage fs(filename, cv::FileStorage::READ);
    fs.getFirstTopLevelNode() >> result;
    return result;
}

1 Answer 1

85

Okay, I'm a dimwit. Here is how it goes:

There is the function convertTo that does exactly what I want.

Thanks for matrix type conversion in opencv for pointing this out.

Here is how I do it:

cv::Mat A = loadMat("mymat.xml"); // See function loadMat in the question!
A.convertTo(A, CV_64F);
2
  • 18
    Also, if you're converting from something like 16U to 8U, you need to add a scaling factor as a third parameter. A.convertTo(A, CV_8UC1, 255.0/65536.0); Nov 20, 2016 at 2:10
  • 6
    (Dimwitticism or not, your question-and-answer allowed me to find the keyword convertTo. It's hard to look something up in the doc without knowing its name!) Note that this example A.convertTo(A, CV_64F) is ambiguous about the direction of the conversion when it is not doing convertion in-place. It is, in fact, source.convertTo(destination, new_type, ...). This is completely in keeping with OpenCV style, but I missed that, had it backwards, and spent a while trying to understand my mistake. Mar 30, 2020 at 20:41

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.