以下是使用C++和OpenCV实现在图像轮廓上打上标签的代码:

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

using namespace std;
using namespace cv;

int main(int argc, char** argv)
{
    Mat img = imread("image.jpg", IMREAD_GRAYSCALE);
    if (img.empty())
    {
        cout << "Could not read the image" << endl;
        return -1;
    }

    // Apply binary thresholding
    Mat thresh;
    threshold(img, thresh, 128, 255, THRESH_BINARY);

    // Find contours
    vector<vector<Point>> contours;
    findContours(thresh, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);

    // Draw labels on contours
    for (int i = 0; i < contours.size(); i++)
    {
        // Compute center of contour
        Moments mu = moments(contours[i]);
        Point2f center(mu.m10 / mu.m00, mu.m01 / mu.m00);

        // Draw label
        putText(img, to_string(i), center, FONT_HERSHEY_SIMPLEX, 1, Scalar(255), 2);
    }

    // Display result
    namedWindow("Contours with Labels", WINDOW_NORMAL);
    imshow("Contours with Labels", img);
    waitKey(0);

    return 0;
}

首先,我们使用imread函数读取输入图像,并将其转换为灰度图像。然后,我们应用二值阈值处理来得到二值图像。接下来,我们使用findContours函数找到轮廓,并将它们存储在一个向量中。最后,我们遍历每个轮廓,计算它们的中心点,并在中心点处打上标签。最后,我们使用imshow函数显示结果图像。

请注意,在此示例中,我们使用的是简单的二值阈值处理和轮廓查找方法。对于更复杂的图像,您可能需要使用更高级的技术来获得更好的结果

C++和opencv实现在图像轮廓上打上标签代码

原文地址: https://www.cveoy.top/t/topic/cnJL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录