You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OpenCV 4.0中如何用cvCreateMat创建cv::Mat共享指针?兼容求助

Migrating cvCreateMat to OpenCV 4.0

Hey there! Let's work through this compatibility hiccup you're hitting after upgrading to OpenCV 4.0. The core issue here is that OpenCV 4.x has largely phased out the old C API functions (like cvCreateMat) in favor of the modern, safer C++ API—so your original 3.4 code won't play nicely anymore.

Why Your Original Code Breaks

Your 3.4 code uses cvCreateMat (a C API tool) to make a CvMat object, then wraps it in a cv::Ptr<CvMat> smart pointer. In OpenCV 4.0, CvMat and most C API utilities are either deprecated or fully removed, so this approach is no longer supported.

Instead of leaning on the outdated C API, use OpenCV's native C++ cv::Mat class paired with cv::makePtr to create your smart pointer. Here's the direct equivalent for OpenCV 4.0:

cv::Ptr<cv::Mat> _pts = cv::makePtr<cv::Mat>(4, 4, CV_32FC2);

A couple of quick notes to clarify:

  • cv::makePtr is the official, preferred way to generate smart pointers for OpenCV objects in 4.x—it handles memory management cleanly, just like your original code intended.
  • If you don't strictly need a smart pointer, you can simplify even further: cv::Mat already uses reference counting to manage its own memory, so this works perfectly too:
    cv::Mat _pts(4, 4, CV_32FC2);
    

Why This Is Better

The C++ cv::Mat class is the backbone of OpenCV's modern ecosystem. It offers stronger type safety, more built-in functionality, and integrates smoothly with other C++ features. Ditching the C API also ensures your code stays compatible with future OpenCV updates.

内容的提问来源于stack exchange,提问作者user11715878

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:34:09