【问题标题】:opencv create mat and add elementsopencv 创建垫子并添加元素
【发布时间】:2016-10-25 22:09:04
【问题描述】:

有一个 jpg 文件,我想把它重新排列成一个 n*3 的 Mat,3 列用于 BGR,n 行用于 jpg 图像中的像素数。

这是我到目前为止所做的。

    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);

}
}
}

在我运行这段代码之前,我尝试了一个简单的 3*3 版本,

    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;

两个输出不同。

[ 43] [232] 这是由于两个 Mats 之间的某些数据类型转换造成的吗? 而且,我不确定这是不是一个好方法,如果有任何更易于管理的方法来做到这一点?

【问题讨论】:

    标签: c++ image opencv image-processing computer-vision


    【解决方案1】:

    你把事情复杂化了。

    要将 3 通道图像 rows x cols 转换为 n x 3,使用 n = rows * cols,您可以简单地使用 reshape,例如:

    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 将是您正在寻找的n x 3


    您很可能需要将datakmeans 一起使用,这需要CV_32F 输入矩阵。然后您可以将data 转换为CV_32F,例如:

    data.convertTo(data, CV_32F);
    

    您可以查看here 以查看kmeans 的示例,该示例还将显示如何将结果恢复为原始形状。

    【讨论】:

    • 这正是我需要的,kmeans!谢谢!
    • 我确实点击了勾号,它是绿色的,是否被接受
    猜你喜欢
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 2015-04-16
    • 1970-01-01
    • 2015-09-29
    • 1970-01-01
    • 2013-03-19
    相关资源
    最近更新 更多