【问题标题】:OpenCV: can't access Mat elementsOpenCV:无法访问 Mat 元素
【发布时间】:2017-03-06 02:30:31
【问题描述】:

我有一个用循环创建的 Mat 对象:

cluster_centre = cv::Mat(num_clusters,num_dimensions,cv::DataType<double>::type) 
// <double> is essential

for (j = 0; j < num_clusters; j++) {
        for (k = 0; k < num_dimensions; k++) {
          ...
          cluster_centre.at<double>(j,k) = ...
          }
}

// rounding numbers 0...255
cluster_centre.convertTo(cluster_centre, CV_32S);

cout &lt;&lt; cluster_centre &lt;&lt; endl的输出是OK的:

 [79, 99, 148;
 73, 29, 14;
 254, 254, 254;
 171, 70, 3;
 178, 189, 211]

而且似乎重塑显然没有效果(colsrows 保持不变):

cluster_centre.reshape(3,1); // storing as 1-D array of 3-channel vectors
cout << cluster_centre.cols //output 3;

当我尝试访问我的元素并进一步绘制 BGR 颜色时,我得到:

cout << Scalar(
    mycolors.at<uchar>(0,0), 
    mycolors.at<uchar>(0,1), 
    mycolors.at<uchar>(0,2))<<endl;

[79, 0, 0, 0] // ??

cout << Scalar(
    mycolors.at<uchar>(0,0), 
    mycolors.at<uchar>(1,0), 
    mycolors.at<uchar>(2,0))<<endl;

[79, 73, 254, 0] //vertical

编辑:矩阵isContinuous,已检查。

【问题讨论】:

  • 不是很清楚...不过看看第二个sn-p here。在我看来,您似乎正在尝试做一些非常相似的事情
  • @Miki cout &lt;&lt; mycolors.at&lt;Vec3b&gt;(0)&lt;&lt;endl; 的输出是一样的:[(first value),0,0]
  • @Miki 在四舍五入之前似乎可以访问浮点数cluster_centre.convertTo(cluster_centre, CV_32S);
  • @Miki 是的! cluster_centre.convertTo(cluster_centre, CV_8U); 工作!谢谢!

标签: c++ opencv mat


【解决方案1】:

函数 Mat::reshape 对 mat 对象本身没有影响。它返回一个被重塑的 cv::Mat 对象。正确的函数调用是:

cluster_centre = cluster_centre.reshape(3,1);

请注意,返回的对象数据指向源对象的数据,即只有头部发生了变化。

【讨论】:

  • 谢谢!是的,看起来我在调用reshape 时出错了,所以现在我可以使用&lt;Vec3b&gt; 颜色向量数组从以前的解决方法切换到正确的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-07
  • 1970-01-01
  • 2011-11-03
  • 2011-09-17
相关资源
最近更新 更多