c++ - 为什么 cv::circle() 只显示在特定 RGB 值的 3D 矩阵上?

标签 c++ opencv

我看到了一些我没有预料到的奇怪行为。在类型为 CV_64FC3(3 个 channel ,浮点值)的纯白色矩阵上,我正在绘制一个彩色圆圈。意想不到的行为是圆圈实际上只显示特定的 RGB 值。这是我的程序针对两种不同颜色的示例输出:

printing a red circle

printing a gray circle

很明显,灰色圆圈不见了。我的问题:为什么?我怎样才能让它出现?下面是我在一个小程序中的示例代码,您可以运行它。

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

void main()
{
    const unsigned int diam = 200;
    cv::namedWindow("test_window");
    cv::Mat mat(diam, diam, CV_64FC3);

    // force assignment of each pixel to white.
    for (unsigned row = 0; row < diam; ++row)
    {
        for (unsigned col = 0; col < diam; ++col)
        {
            mat.at<cv::Vec3d>(row, col)[0] = 255;
            mat.at<cv::Vec3d>(row, col)[1] = 255;
            mat.at<cv::Vec3d>(row, col)[2] = 255;
        }
    }

    // big gray circle.
    cv::circle(mat, cv::Point(diam/2, diam/2), (diam/2) - 5, CV_RGB(169, 169, 169), -1, CV_AA);

    cv::imshow("test_window", mat);
    cv::waitKey();
}

最佳答案

您正在使用浮点矩阵类型。来自 opencv docs :

If the image is 32-bit floating-point, the pixel values are multiplied by 255. That is, the value range [0,1] is mapped to [0,255].

这是工作代码:

#include <opencv2/opencv.hpp>

void main()
{
    const unsigned int diam = 200;
    cv::namedWindow("test_window");
    // force assignment of each pixel to white.
    cv::Mat3b mat = cv::Mat3b(diam, diam, cv::Vec3b(255,255,255));

    // big gray circle.
    cv::circle(mat, cv::Point(diam/2, diam/2), (diam/2) - 5, CV_RGB(169, 169, 169), -1, CV_AA);

    cv::imshow("test_window", mat);
    cv::waitKey();
}

结果:

screenshot

更新。

  1. 不要使用循环来填充矩阵。上面示例中的 Mat::zeros()、Mat::ones() 和构造函数看起来好多了。U
  2. 使用特殊的 cv::MatXY 类型来防止错误类型的运行时错误。

关于c++ - 为什么 cv::circle() 只显示在特定 RGB 值的 3D 矩阵上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13918143/

相关文章:

c++ - 是否可以在调用析构函数时将指向类实例的指针设置为 nullptr?

c++ - 带汇编的有序二进制搜索 |递归与迭代与库

opencv - 使用Tesseract OCR读取错误

python - cv2.imshow 图像窗口放置在可视屏幕之外

c++ - 从一个线程中捕获 OpenCV 相机

c++ - Opencv_traincascade 卡住

c++ - 如何在不使用++ 或 + 或其他算术运算符的情况下将两个数字相加

c++ - 当 JSON 中存在非法字符时,如何防止 JSON 解析器崩溃?

c++ - Ankerl快速指数算法简单解释

C++ 应用程序控制台未退出