Opencv Mat的元素索引产生垃圾

Opencv Mat's element indexing producing garbage

本文关键字:索引 Mat 元素 Opencv      更新时间:2023-10-16

我正在沿边缘收集一堆像素,然后将它们保存在矩阵中。

    cv::Mat vals = cv::Mat(18,7,img.type(),cv::Scalar(0));
    for (int j=1; j<7; j++)
    {
      cv::Point2f coords = start + direction*(step_size*j) - 3*normal;
      cv::Point2f coords_successive = coords + direction - 3*normal;
      cv::Point2f coords_previous = coords - direction - 3*normal;
      for (int y=0; y<7; y++)
      {
        vals.at<int>((j-1)*3, y) = 1;    //this->sample(img, coords_previous+=normal);
        vals.at<int>((j-1)*3+1, y) = 1;  //this->sample(img, coords+=normal);
        vals.at<int>((j-1)*3+2, y) = 1;  //this->sample(img, coords_successive+=normal);
      }
    }
    std::cout << "----" << std::endl;
    for (int x=0; x<18; x++)
    {
        for (int y=0; y<7; y++) 
        {
            std::cout << vals.at<int>(x,y) << "t";
        }
        std::cout << std::endl;
    }

结果:

1 1 1 1 1 257 256256 256 256 65792 65536 65536 65536
65536 16842752 16777216 16777216 16777216 16777216 16777216
1 1 1 1 1 257 256256 256 256 65792 65536 65536 65536
65536 16842752 16777216 16777216 16777216 16777216 16777216
1 1 1 1 1 257 256256 256 256 65792 65536 65536 65536
65536 16842752 16777216 16777216 16777216 16777216 16777216
1 1 1 1 1 257 256256 256 256 65792 65536 65536 65536
65536 16842752 16777216 16777216 16777216 16777216 16777216
1 1 1 1 1 257 256256 256 256 65792 65536 65536 65536
65536 16842752 16777216 16777216 16777216 16777216 16777216
1 1 1 1 1 1 1 1
256 256 256 256 256 0 1
65536 65536 65536 0 256 0 1

我已经尝试过:1)UCHAR而不是INT,如使用灰度图像时在其他帖子中所建议的那样,2)使用int [] []矩阵(正在工作!)并将数据传递到矩阵(正在产生相同的垃圾)3)倒置索引(我想"好吧,也许是我在未定义矩阵的地方进行值),但是...相同的垃圾。

在打印垫子结构时,您正在混淆行和列。您可以使用以下代码。如果您的图像为8UC1频道,则必须使用UCHAR访问。vals.at(i,j)。但是您还没有指定什么是img.type()。我假设是CV_8UC1

 cv::Mat vals = cv::Mat(18,7,img.type(),cv::Scalar(0));
for (int j=1; j<7; j++)
{
  cv::Point2f coords = start + direction*(step_size*j) - 3*normal;
  cv::Point2f coords_successive = coords + direction - 3*normal;
  cv::Point2f coords_previous = coords - direction - 3*normal;
  for (int y=0; y<7; y++)
  {
    vals.at<int>((j-1)*3, y) = 1;    //this->sample(img, coords_previous+=normal);
    vals.at<int>((j-1)*3+1, y) = 1;  //this->sample(img, coords+=normal);
    vals.at<int>((j-1)*3+2, y) = 1;  //this->sample(img, coords_successive+=normal);
  }
}
std::cout << "----" << std::endl;
int rows=vals.rows;
int colms=vals.cols;
for (int x=0; x<rows; x++)
{
    for (int y=0; y<colms; y++) 
    {
        std::cout << vals.at<uchar>(x,y) << "t";
    }
    std::cout << std::endl;
}

cv:Scalar通常为类型double

,第一个索引通常是行,第二个是列。这在图像处理中通常是