重塑OpenCV Mat失败

Sea*_*123 2 c++ opencv matrix

我无法重塑我的形象cv::Mat.

这是我的代码.

#include "opencv2/core/core.hpp"
#include "opencv2/contrib/contrib.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/objdetect/objdetect.hpp"
#include <boost/algorithm/string.hpp>
#include <stdlib.h>
#include <vector>
#include <string>
#include <assert.h>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <iterator>
#include <sstream>



int main(int argc, const char* argv[])
{
    std::cout << "Start\n";
    cv::Mat eigenvectors = (cv::Mat_<float>(2,2) << 4, 3, 2, 1);
    std::cout << "eigenvectors shape " << eigenvectors.size() << std::endl;
    cv::Mat reshaped = eigenvectors.reshape(4, 1);
    std::cout << reshaped.size() << std::endl;
    std::cout << reshaped << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

这是结果.

Start
eigenvectors shape [2 x 2]
[1 x 1]
[4, 3, 2, 1]
Run Code Online (Sandbox Code Playgroud)

为什么我的程序声称拥有1x1矩阵,但是保持4x1矩阵的值?它只针对这个维度这样做.

当我扩展我的代码以包含这些测试时.

reshaped = eigenvectors.reshape(1, 4);
std::cout << reshaped.size() << std::endl;
std::cout << reshaped << std::endl;
reshaped = eigenvectors.reshape(2, 2);
std::cout << reshaped.size() << std::
Run Code Online (Sandbox Code Playgroud)

我得到了正常的结果.

[1 x 4]
[4; 3; 2; 1]
[1 x 2]
[4, 3; 2, 1]
Run Code Online (Sandbox Code Playgroud)

这是一个错误还是我做错了什么?

编辑:

为了提高Google对此结果的相关性,我遇到的另一个症状是,由于我的"重塑",我也失去了我的类型Mat.

kaz*_*rey 6

确保您完全了解reshape()传递给方法的参数的效果和含义.以下是OpenCV文档中的文章:

Mat Mat::reshape(int cn, int rows=0) const

Parameters:   

    cn – New number of channels. If the parameter is 0, the number of channels remains the same.
    rows – New number of rows. If the parameter is 0, the number of rows remains the same.
Run Code Online (Sandbox Code Playgroud)

因此,在您的第一个代码片段中,您eigenvectors通过四个元素初始化:reshape()4,3,2,1.为这些元素创建另一个给定大小参数的矩阵.

cv::Mat reshaped = eigenvectors.reshape(4, 1);- 在这里,你得到[1x1]4通道矩阵.所有元素都存储在reshaped矩阵的单个4通道元素中,就像输出所示.要创建具有所需行数和列数的矩阵,请相应地设置通道和列的数量.例如,如果存在大小为1通道的matix,[4x4]并且您希望它有2行8列,则只需调用即可reshape(1,2).

希望能帮助到你.

  • 以防万一在解决方案中不清楚(我肯定错过了它).我的错误是让"渠道"与列混淆.我通过传入`cn = 1`并传入所需的行号来解决我的问题. (2认同)