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

如何将OpenCV中的vector<vector<Point>>转换为vector<vector<Point2f>>

OpenCV 中 Contour 点类型(Point → Point2f)的简便转换方法

针对从cv::findContours得到的vector<vector<Point>>类型轮廓数据,要转换为vector<vector<Point2f>>,这里提供几种高效简洁的实现方式:

方法1:利用vector范围构造函数(最简洁)

直接通过vector的范围构造,借助OpenCV内置的Point到Point2f的隐式转换(Point2f支持接收int类型的坐标参数),一行代码完成单个轮廓的转换:

vector<vector<Point>> contours;
// 假设已通过cv::findContours填充contours

vector<vector<Point2f>> new_contours;
new_contours.reserve(contours.size()); // 预分配空间避免频繁内存分配

for (const auto& cnt : contours) {
    // 用原contour的迭代器直接构造Point2f类型的vector
    new_contours.emplace_back(cnt.begin(), cnt.end());
}

方法2:嵌套std::transform(函数式风格)

如果偏好函数式编程,可以用两层std::transform完成二维vector的类型转换:

vector<vector<Point>> contours = ...;
vector<vector<Point2f>> new_contours;
new_contours.reserve(contours.size());

std::transform(contours.cbegin(), contours.cend(), std::back_inserter(new_contours),
    [](const vector<Point>& cnt) {
        vector<Point2f> temp;
        temp.reserve(cnt.size());
        std::transform(cnt.cbegin(), cnt.cend(), std::back_inserter(temp),
            [](const Point& p) { return cv::Point2f(p.x, p.y); });
        return temp;
    });

关于push_back报错的原因

你之前尝试用push_back直接转换时编译报错,大概率是因为直接将vector<Point>类型的元素推入vector<vector<Point2f>>——这两种vector类型不兼容,编译器无法自动完成容器层面的类型转换,必须逐个元素完成Point到Point2f的转换后再构造内层vector。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 12:35:27