简体   繁体   English

cv :: Mat使用数组初始化

[英]cv::Mat initialization using array

I experienced a strange behavior after for example initializing through 例如,通过初始化后,我遇到了奇怪的行为

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

int main() {
    cv::Mat h = cv::Mat(2, 2, CV_32F, {1.0, 2.0, 1.0, 0.0});
    std::cout << h << std::endl;
    return 0;
}

cout prints out [1, 1; cout打印出[1,1; 1, 1]. 1,1]。 WTF just happened? WTF刚发生? I'm using eclipse on ubuntu, gcc version 5.4, OpenCV 3.2 我在ubuntu,gcc版本5.4,OpenCV 3.2上使用eclipse

You're not using a valid Mat constructor. 您没有使用有效的Mat构造函数。 You have a few options: 您有几种选择:

  1. From an array: 从数组中:

     float pf[] = { 1.f, 2.f, 3.f, 4.f }; Mat1f m1(2, 2, pf); 

    or 要么

     std::vector<float> vf = { 1.f, 2.f, 3.f, 4.f }; Mat1f m2(2, 2, vf.data()); 
  2. With comma initializers: 使用逗号初始值设定项:

     Mat1f m3 = (Mat1f(2, 2) << 1.f, 2.f, 3.f, 4.f); 
  3. If the matrix is small, you can use Matx : 如果矩阵很小,则可以使用Matx

     Matx22f m4(1.f, 2.f, 3.f, 4.f); 

Note that a Mat1f is a typedef for Mat_<float> , which is a Mat of type CV_32FC1 . 请注意, Mat1fMat_<float>的typedef,它是CV_32FC1类型的Mat


Using your method doesn't work because {1.0, 2.0, 1.0, 0.0} constructs cv::Scalar , so you call the constructor Mat(int rows, int cols, int type, cv::Scalar) . 使用您的方法不起作用,因为{1.0, 2.0, 1.0, 0.0}构造cv::Scalar ,因此您调用了构造函数Mat(int rows, int cols, int type, cv::Scalar) Since you have only 1 channel, the matrix is initialized with the first value of this scalar, which is the first value in your initializer list. 由于只有一个通道,因此矩阵将使用此标量的第一个值初始化,这是初始化程序列表中的第一个值。

Note that this is just a coincidence since your matrix has 4 elements (the maximum number supported by Scalar s). 请注意,这只是一个巧合,因为您的矩阵有4个元素( Scalar支持的最大数量)。 If you use a higher number of elements: 如果您使用更多元素:

cv::Mat h(2, 3, CV_32F, {3.f, 2.f, 1.f, 0.f, 2.f, 5.f});

the code should not compile. 该代码不应该编译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM