ZBLOG

C++ opencv 图像最外侧非零点提取

要在 C++ 中使用 OpenCV 提取图像的最外侧非零点,可以按照以下步骤进行:

  1. 读取图像:加载待处理的图像。
  2. 转换为灰度图:如果是彩色图像,将其转换为灰度图。
  3. 二值化处理:通过阈值处理将图像转换为二值图(黑白)。
  4. 检测轮廓:使用 findContours 函数获取所有轮廓。
  5. 提取最外侧非零点:找到最外层轮廓的点。

下面是具体实现代码:

#include <opencv2/opencv.hpp>
#include <vector>

int main() {
    // 读取图像
    cv::Mat img = cv::imread("path_to_your_image.jpg");
    if (img.empty()) {
        std::cerr << "Error: Could not open or find the image!" << std::endl;
        return -1;
    }

    // 转换为灰度图
    cv::Mat gray;
    cv::cvtColor(img, gray, cv::COLOR_BGR2GRAY);

    // 二值化处理
    cv::Mat binary;
    cv::threshold(gray, binary, 127, 255, cv::THRESH_BINARY | cv::THRESH_OTSU);

    // 检测轮廓
    std::vector<std::vector<cv::Point>> contours;
    std::vector<cv::Vec4i> hierarchy;

    cv::findContours(binary, contours, hierarchy, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);

    // 确保至少有一个轮廓被找到
    if (contours.empty()) {
        std::cout << "No contours found!" << std::endl;
        return 0;
    }

    // 找到最大的轮廓(最外层)
    int largestContourIndex = -1;
    double maxArea = 0;

    for (size_t i = 0; i < contours.size(); i++) {
        double area = cv::contourArea(contours[i]);
        if (area > maxArea) {
            maxArea = area;
            largestContourIndex = static_cast<int>(i);
        }
    }

    if (largestContourIndex != -1) {
        // 在原始图像上标记最外侧非零点
        for (const auto& point : contours[largestContourIndex]) {
            img.at<cv::Vec3b>(point) = cv::Vec3b(0, 255, 0); // 将最外侧的非零点标记为绿色

            // 输出这些点的位置
            std::cout << "Outer point: (" << point.x << ", " << point.y << ")" << std::endl;
        }

        // 显示结果
        cv::imshow("Original Image with Outer Points", img);
        cv::waitKey(0);
        
      } else {
          std::cout << "No contour found!" << std::endl;
      }

      return 0;
}

注意事项:

  • 请确保已安装 OpenCV 库,并正确配置开发环境。
  • 替换 "path_to_your_image.jpg" 为实际图片路径。
  • 根据需要调整阈值以获得最佳效果,尤其是在不同的光照条件下。

功能扩展:

此代码提取了最大轮廓并在原始图像中标记了其边界上的非零点。您可以根据需求进一步修改代码,例如保存这些点的信息或进行其他处理。


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=18683

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?