将像素存储在二维数组中(以矩阵形式)
Storing pixels in a 2D Array (in a matrix form)
我想将图像中水平像素和垂直像素的总数存储在二维数组中。使用 opencv 在 c++ 中执行此操作的语法应该是什么?这是我使用 opencv 库在 C++ 中编写的代码。
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];
它给我一个错误说明:
array bound is not an integer constant before ‘]’ token int squares[IDIM][JDIM]; ^ array bound is not an integer constant before ']' token int squares[IDIM][JDIM]; ^
执行此操作的正确方法应该是什么?
你的错误是因为 IDIM
和 JDIM
的值不是编译时常量。因此,您必须动态分配数组 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?
我想将图像中水平像素和垂直像素的总数存储在二维数组中。使用 opencv 在 c++ 中执行此操作的语法应该是什么?这是我使用 opencv 库在 C++ 中编写的代码。
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];
它给我一个错误说明:
array bound is not an integer constant before ‘]’ token int squares[IDIM][JDIM]; ^ array bound is not an integer constant before ']' token int squares[IDIM][JDIM]; ^
执行此操作的正确方法应该是什么?
你的错误是因为 IDIM
和 JDIM
的值不是编译时常量。因此,您必须动态分配数组 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?