Slowpoke
Slowpoke

Reputation: 1079

OpenCV: can't access Mat elements

I have a Mat object that is created with a loop:

cluster_centre = cv::Mat(num_clusters,num_dimensions,cv::DataType<double>::type) 
// <double> is essential

for (j = 0; j < num_clusters; j++) {
        for (k = 0; k < num_dimensions; k++) {
          ...
          cluster_centre.at<double>(j,k) = ...
          }
}

// rounding numbers 0...255
cluster_centre.convertTo(cluster_centre, CV_32S);

The output of cout << cluster_centre << endl is OK:

 [79, 99, 148;
 73, 29, 14;
 254, 254, 254;
 171, 70, 3;
 178, 189, 211]

And it seems that reshaping has apparently no effect (cols and rows stay the same):

cluster_centre.reshape(3,1); // storing as 1-D array of 3-channel vectors
cout << cluster_centre.cols //output 3;

And when I try to access my elements and paint BGR color further I get:

cout << Scalar(
    mycolors.at<uchar>(0,0), 
    mycolors.at<uchar>(0,1), 
    mycolors.at<uchar>(0,2))<<endl;

[79, 0, 0, 0] // ??

cout << Scalar(
    mycolors.at<uchar>(0,0), 
    mycolors.at<uchar>(1,0), 
    mycolors.at<uchar>(2,0))<<endl;

[79, 73, 254, 0] //vertical

EDIT: The matrix isContinuous, checked.

Upvotes: 0

Views: 412

Answers (1)

Tobias Senst
Tobias Senst

Reputation: 2830

The function Mat::reshape has no effect on the mat object itself. It returns an cv::Mat object which is reshaped. The correct function call would be:

cluster_centre = cluster_centre.reshape(3,1);

Please note that the returned object data points to the data of the source object, i.e. only the header has changed.

Upvotes: 1

Related Questions