【问题标题】:Storing pixels in a 2D Array (in a matrix form)将像素存储在二维数组中(以矩阵形式)
【发布时间】:2017-03-02 16:05:34
【问题描述】:

我想将图像中水平像素和垂直像素的总数存储在二维数组中。使用opencv在c ++中执行此操作的语法应该是什么?这是我在 C++ 中使用 opencv 库编写的代码。

using namespace std;
using namespace cv;

Mat image=imread("task1-1.png");

const int IDIM = image.rows; // horizontal size of the squares
const int JDIM = image.cols; // vertical size size of the squares                                                                                                                                   

int squares[IDIM][JDIM];

它给了我一个错误说明:

数组边界在']'标记之前不是整数常量 int squares[IDIM][JDIM]; ^ 数组边界在 ']' 标记 int squares[IDIM][JDIM] 之前不是整数常量; ^

执行此操作的正确方法应该是什么?

【问题讨论】:

  • “^”标记两次都指向“]”标记。
  • 不要。像其他人一样使用平面内存缓冲区。
  • 为什么要使用二维数组,你已经有了Mat。你真的需要它还是你认为你需要它?
  • 其实我需要获取障碍物中的所有节点,起点,终点,可移动区域,以便使用A*算法找到最短路径。

标签: c++ image-processing opencv3.0


【解决方案1】:

您的错误是因为 IDIMJDIM 的值不是编译时常量。因此,您必须动态分配数组 squares 或使用替代方法,例如 vector

动态分配数组

// Allocate

int** squares = new int*[image.rows];

for(int x = 0; x < image.rows; ++x)
{
    squares[x] = new int[image.cols];

    for(int y = 0; y < image.cols; ++y)
    {
        squares[y] = 0;
    }
}

// Use

squares[0][1] = 5;

// Clean up when done

for(int x = 0; x < image.rows; ++x)
{
    delete[] squares[x];
}

delete[] squares;
squares = nullptr;

矢量

// Allocate

std::vector<std::vector<int>> squares(image.rows, std::vector<int>(image.cols, 0));

// Use

squares[0][1] = 5;

// Automatically cleaned up

How do I declare a 2d array in C++ using new?

【讨论】: