Reputation: 53
I want to store the total number of horizontal pixels and vertical pixels in an image in a 2D Array. What should be the syntax to carry this out in c++ using opencv? This is my code in C++ using opencv libraries.
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];
It gives me an error stating:
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]; ^
What should be the correct way to carry this out?
Upvotes: 0
Views: 1466
Reputation: 6597
Your error is because the values of IDIM
and JDIM
are not compile-time constant. So you must either dynamically allocate your array squares
or use an alternative approach, such as a vector
.
Dynamically Allocated Array
// 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;
Vector
// Allocate
std::vector<std::vector<int>> squares(image.rows, std::vector<int>(image.cols, 0));
// Use
squares[0][1] = 5;
// Automatically cleaned up
See How do I declare a 2d array in C++ using new?
Upvotes: 2