-1

The following piece of code does not seem to work. There is a similar question here How to fill Matrix with zeros in OpenCV? but, I want a 1-D mat, not a 2-D mat as mentioned in this link.

int histSize = 8;
Mat colorHist;

for (int i = 0; i < (histSize * histSize * histSize); i++)
    colorHist.at<float>(i) = 0.0;
Community
  • 1
  • 1
LeviAckerman
  • 189
  • 2
  • 6

2 Answers2

2

You may try something like that:

1 - First you create a float array which is your 1-D data structure:

float arr[10] = {0}; // initialize it to all 0`s

2 - Now create your opencv matrix as follows and fill the array into it:

cv::Mat colorHist = cv::Mat(2, 4, CV_32F, arr);

3 - if you want to access individual entries use something like:

for(int i=0; i<10; i++) {
    colorHist.at<float>(0,i);
}

where i is the index of the entry you want from 0 to 9.

or just:

colorHist.at<float>(0,2);

if you need individually. here we get the entry with index 2 which will return 0 of course since the matrix is all zeros at that point.

EDIT: As Nicholas suggested:

cv::Mat colorHist = cv::Mat::zeros(1, 10, CV_32F); // size=10

is a shorter way of creating a 1-D row matrix with all zeros if you do not want to deal with a float array (credits go to Nicholas). and access is of course:

for(int i=0; i<10; i++) {
    colorHist.at<float>(i);
}

Hope that helps!

erol yeniaras
  • 3,701
  • 2
  • 22
  • 40
2

In the code you have posted, you have not initialized the Mat to any size or type. However, there is a very easy way to initialize a matrix with zeros.

Initialising Matrix values to 0:

cv::Mat colorHist = cv::Mat::zeros(1, histSize, CV_32F);

This will produce a row vector (1-dimensional) with histSize columns, CV_32F simply refers to the data type the matrix is dealing with (float in this case).

If you wish to work with column vectors instead, simply swap the dimensions:

cv::Mat colorHist = cv::Mat::zeros(histSize, 1, CV_32F);

Accessing elements:

for(int i = 0; i < histSize; i++)
    float c = colorHist.at<float>(i);
Nicholas Betsworth
  • 1,707
  • 19
  • 24