在 OpenCV 上获取特定的行值

Getting specific Line values on OpenCV

本文关键字:OpenCV 获取      更新时间:2023-10-16

我正在尝试访问视频中的行值。我已经找到了如何使用以下代码在屏幕上打印所有值,但我需要的是仅在出现值 255(白色(时打印。

    LineIterator li1(fgThreshold, Point(20, 0), Point(20, 479), 8); 
    vector<Vec3b> buf1;
    for (int i = 0; i<li1.count; i++) { 
        buf1.push_back(Vec3b(*li1));
        li1++;
    }
    cout << Mat(buf1) << endl;

原因是当白色(由threshold生成(越过线时,我需要保存帧。

如果您正在处理阈值图像,则其类型为 CV_8UC1 ,并且其元素是 uchar ,而不是 Vec3b

在这种情况下,您可以检查行迭代器的值是否为白色 (255(,如下所示:

#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
    // Create a CV_8UC1 Mat with a white circle
    // Your fgThreshold would be something like this
    Mat1b fgThreshold(100, 100, uchar(0));
    circle(fgThreshold, Point(20, 20), 3, Scalar(255), CV_FILLED);
    // Init line iterator
    LineIterator lit(fgThreshold, Point(20, 0), Point(20, 40));
    // Value to check
    const uchar white = 255;
    // Save colors in buf, if value is ok
    vector<uchar> buf;
    // Save points in pts, if value is ok
    vector<Point> pts;
    for (int i = 0; i < lit.count; ++i, ++lit)
    {
        // Check if value is ok
        if (**lit == white)
        {
            // Add to vectors
            buf.push_back(**lit);
            pts.push_back(lit.pos());
        }
    }
    // Print
    cout << "buf: " << Mat(buf) << endl;
    cout << "pts: " << Mat(pts) << endl;
    return 0;
}

如果您正在处理CV_8UC3图像,则需要转换行迭代器,例如:

#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
    Mat3b fgThreshold(100, 100, Vec3b(0,0,0));
    circle(fgThreshold, Point(20, 20), 3, Scalar(255, 255, 255), CV_FILLED);
    LineIterator lit(fgThreshold, Point(20, 0), Point(20, 40));
    const Vec3b white(255, 255, 255);
    vector<Vec3b> buf;
    vector<Point> pts;
    for (int i = 0; i < lit.count; ++i, ++lit)
    {
        // Cast to Vec3b
        if ((Vec3b)*lit == white)
        {
            // Cast to Vec3b
            buf.push_back((Vec3b)*lit);
            pts.push_back(lit.pos());
        }
    }
    cout << "buf: " << Mat(buf) << endl;
    cout << "pts: " << Mat(pts) << endl;
    return 0;
}