c++ - 如何在openCV中获取像素矩阵和 reshape 矩阵

标签 c++ image-processing opencv matrix

我正在使用 openCV 在 C++ 中实现图像处理算法,其中第一步要求将图像转换为矩阵。我知道当图像加载到 openCV 中时,它已经存储为矩阵。我使用的图像大小为 80 x 60,因此我假设存储它的矩阵大小为 80 x 60。但是,我希望首先能够看到这个矩阵,然后能够 reshape 它变成一个具有相同编号的矩阵。像素,而是作为一长列。即 80 x 60 矩阵现在将变为 4800 x 1 矩阵。我曾尝试研究教科书和在线,但无济于事。到目前为止,这是我的代码。在任何情况下,它都不起作用,因为我无法从 'IplImage *' 转换为 'CvMat * 但是我应该如何在创建矩阵后将我的像素值分配给矩阵?拜托,如果有人可以帮助我使用此代码,我将不胜感激。

#include "cv.h"
#include "highgui.h"
#include "iostream"

using namespace std;
int main( int argc, char* argv ) {
IplImage* img0 = NULL;
CvMat* img0_mat = NULL ;
img0 = cvLoadImage("C:\\new\\walk mii.jpg");
if (!img0){
    return -1;}
img0_mat = cvCreateMat(80, 60, 1);
img0_mat = img0;
cout <<" matrix " << img0 << endl;

cvWaitKey(0);
return 0;
}

最佳答案

您可以调用 Mat::reshape(int cn, int rows=0) :

The method makes a new matrix header for *this elements. The new matrix may have different size and/or different number of channels. Any combination is possible, as long as:

1) No extra elements is included into the new matrix and no elements are excluded. Consequently, the product

2) rows*cols*channels() must stay the same after the transformation.

No data is copied, i.e. this is O(1) operation. Consequently, if you change the number of rows, or the operation changes elements’ row indices in some other way, the matrix must be continuous. See Mat::isContinuous() .

...看起来您使用的是旧版本的库,所以您需要 cvReshape .这样的事情应该有效:

#include "cv.h" 
#include "highgui.h" 
#include "iostream" 
using namespace std; 

int main( int argc, char* argv ) 
{ 
    IplImage* img0 = NULL; 
    CvMat* img0_mat = NULL ; 
    img0 = cvLoadImage("C:\\new\\walk mii.jpg"); 
    img0_mat = cvCreateMat(80, 60, 1); 

    CvMat row_header, *row;
    row = cvReshape( img0_mat, &row_header, 0, 1 );

    cout << " matrix " << row->tostring() << endl; 

    cvWaitKey(0); 
    return 0;
}

关于c++ - 如何在openCV中获取像素矩阵和 reshape 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9630013/

相关文章:

c++ - 如何向模板类公开统一接口(interface)?

c++ - C++中的自动引用

matlab - 扩展matlab中的subplot函数

c++ - OpenCV 图像减法

java - 如何使用 OpenCV 和 Java 检测图像/倒置图像中的倒置文本

c++ - 从其他窗口(Qt)释放窗口?

c++ - QQmlEngine 和 cmake

python - 如何使nii图像的深度相等?

matlab - 通过PCA降维后无法生成原始数据

opencv绘制二维直方图