c++ - 如何打印 vector 中的元素

标签 c++ opencv

我正在尝试计算下面骨架化图像中的端点数。我在这里使用 vector 。我需要的是打印 vector ,而不仅仅是计数。我尝试了很多方法。但是没有用。我是 open cv 的新手,我从互联网上找到了以下代码。谁能帮我打印这段代码实际得到的 vector 。代码如下。

// get the end points
    // Declare variable to count neighbourhood pixels
    int count, numberOFEndpoints;

    // To store a pixel intensity
    uchar pix;
    numberOFEndpoints = 0;
    // To store the ending co-ordinates
    std::vector<int> coords;

    // For each pixel in our image...
    for (int i = 1; i < CopyofSkeletionize.rows - 1; i++) {
        for (int j = 1; j < CopyofSkeletionize.cols - 1; j++) {

            // See what the pixel is at this location
            pix = CopyofSkeletionize.at<uchar>(i, j);

            // If not a skeleton point, skip
            if (pix == 0)
                continue;

            // Reset counter
            count = 0;

            // For each pixel in the neighbourhood
            // centered at this skeleton location...
            for (int y = -1; y <= 1; y++) {
                for (int x = -1; x <= 1; x++) {

                    // Get the pixel in the neighbourhood
                    pix = CopyofSkeletionize.at<uchar>(i + y, j + x);


                    // Count if non-zero
                    if (pix != 0)
                        count++;
                }
            }

            // If count is exactly 2, add co-ordinates to vector
            if (count == 2) {
                coords.push_back(i);
                coords.push_back(j);
                numberOFEndpoints = numberOFEndpoints + 1;
            }

        }
    }
     printf("numberOFEndpoints : %d \n", numberOFEndpoints);

我在互联网上使用了这段代码,但没有用。对于 (int i = 0; i < coords.size()/2; i++) 输出 << "( "<

/image/CMZtu.png

最佳答案

首先...您想以更好的方式存储坐标。也许像两个 vector :

std::vector<int> coordx;
std::vector<int> coordy;

然后你只需打印它:

for (int i = 0; i < coordx.size(); ++i)
    std::cout << coordx[i] << " x " << coordy[i] << std::endl;

或者使用 pair (可能需要 #include <pair> )或创建自定义 point结构:

std::vector< std::pair<int, int> > coords;

添加到坐标 vector 会是这样的:

coords.push_back(std::make_pair(x, y));

然后你只需打印它:

for (int i = 0; i < coords.size(); ++i)
    std::cout << coords[i].first << " x " << coords[i].second << std::endl;

其次...如果你坚持使用单vector<int> , 尝试:

int i = 0;
while (i < coord.size())
    std::cout << coords[i++] << " x " << coords[i++] << std::endl;

关于c++ - 如何打印 vector 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42288931/

相关文章:

OpenCV 图像融合

visual-studio-2008 - OpenCV级联分类器教程异常

python-3.x - 不能将 OpenCV GeneralizedHoughTransform 类与 Python 一起使用

c++ - 从 <cv::vec3b> vector 中分别获取 R、G、B

c++ - Qt 自动连接操作

c++ - 使用引用指针中的信息填充 vector

c++ - 类函数 toString() C++

opencv - OpenCV(和其他地方)中使用的 Scharr-Filter 中的值的解释

c++ - OpenCV : findcontours() , 外部轮廓太多

c++ - std::getline:定界字符与字符数