0

There is a jpg file, I would like to rearrange it into a Mat of n*3, 3 columns for BGR, n rows for number of pixels in the jpg image.

Here is what I did so far.

    Mat img = imread(test.jpg);
    Mat imgHSV;
    cvtColor(img, imgHSV, COLOR_BGR2HSV);
    vector<Mat> imgHSV_split;
    split(imgHSV,imgHSV_split);   //split the 3 channel image into 3 single channel mats

Mat img_combind_feature(imgHSV.rows*imgHSV.cols(),3,CV_8UC1);
for(int i=0; i < imgHSV.row; i++){
for(int j=0; j < imgHSV.col; j++){


for (int k=0; k<3; k++){


img_combind_feature.row(l).col(k) = imgHSV_split[k].row(i).col(j);

}
}
}

Before I run this code, I tried a simple 3*3 version,

    Mat img = imread(test.jpg);
    Mat imgHSV;
    cvtColor(img, imgHSV, COLOR_BGR2HSV);
    vector<Mat> imgHSV_split;
    split(imgHSV,imgHSV_split);   //split the 3 channel image into 3 single channel mats

Mat img_combind_feature(1,3,CV_8UI1);   
img_combind_feature.row(0).col(0) = imgHSV_split[0].row(0).col(0);

img_combind_feature.row(0).col(1) = imgHSV_split[1].row(0).col(0);

img_combind_feature.row(0).col(2) = imgHSV_split[2].row(0).col(0);


cout << imgHSV_split[0].row(0).col(0) << endl;
cout << img_combind_feature.row(0).col(0) << endl;

The two outputs are different.

[ 43] [232] Is this due to some data type translation between the two Mats? And, I am not sure this is a good way to do it, if there are any more manageable ways to do this?

tomu
  • 144
  • 1
  • 11

1 Answers1

1

You're overcomplicating this.

To turn a 3 channel image rows x cols to a n x 3, with n = rows * cols, you can simply use reshape like:

Mat img = ... // 3 channels

int n = img.rows * img.cols;
Mat data = img.reshape(1, n); // 1 channel, n rows, the # of cols will be automaticallt set to 3.

data will be the n x 3 you are looking for.


Most likely, you need to use data with kmeans, which needs a CV_32F input matrix. Then you can convert data to CV_32F like:

data.convertTo(data, CV_32F);

You can have a look here for an example with kmeans, that will show also how to restore the result into the original shape.

Community
  • 1
  • 1
Miki
  • 40,887
  • 13
  • 123
  • 202