【发布时间】:2021-01-21 01:51:56
【问题描述】:
我在 OpenCV 中将 Mat OpenCV 矩阵 (2D) 转换为 1D 数组时遇到了一些困难。我正在使用 Visual Studio 在 C++ 中实现我的代码,我的环境是 Windows 10。 这是我的代码
include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include "opencv2/opencv.hpp"
#include <iostream>
#include <vector>
using namespace std;
using namespace cv;
int countt = 1;
int main()
{
std::cout << "The program starts!\n";
// Create a VideoCapture object and open the input file
// If the input is the web camera, pass 0 instead of the video file name
VideoCapture cap("Control1.avi");
// Check if camera opened successfully
if (!cap.isOpened()) {
cout << "Error opening video stream or file" << endl;
return -1;
}
// Size of the video
Size capSize = Size((int)cap.get(CAP_PROP_FRAME_WIDTH),
(int)cap.get(CAP_PROP_FRAME_HEIGHT));
cout << "Frame Size: " << capSize << endl;
cout << "Number of Frames: " << cap.get(CAP_PROP_FRAME_COUNT) << endl;
while (1) {
Mat frame;
// Capture frame-by-frame
cap >> frame;
// If the frame is empty, break immediately
if (frame.empty())
break;
//converting Mat frame into 1D array
int* testData1D = (int*)frame.data;
cout << "1Darray: " << testData1D[22] << endl;
// Display the resulting frame
imshow("Frame", frame);
cout << "Count = " << countt << endl;
countt = countt + 1;
// Press ESC on keyboard to exit
char c = (char)waitKey(25);
if (c == 27)
break;
}
// When everything done, release the video capture object
cap.release();
// Closes all the frames
destroyAllWindows();
return 0;
}
此代码不成功。我无法从数组中打印出合理的数据。这是我在运行代码时得到的一种东西:1Darray: 134742016。这假设是像素的强度(介于 0 和 255 之间)。
我还用下面的代码替换了int* testData1D = (int*)frame.data;,以便将矩阵内容一一转换成数组:
int numCols = frame.cols;
int numRows = frame.rows;
const int frameSize = frame.cols * frame.rows;
double frameArray[201*204];
for (int x = 0; x < numCols; x++) { // x-axis, cols
for (int y = 0; y < numRows; y++) { // y-axis rows
double intensity = frame.at<uchar>(Point(x, y));
frameArray[x * frame.cols + y] = intensity;
}
}
但我最终得到了一个永远不会结束的无限 for 循环。 (程序永远运行) 我在 Stackoverflow 上检查了一堆其他代码,例如 c++ OpenCV Turn a Mat into a 1 Dimensional Array 和 Convert Mat to Array/Vector in OpenCV
但它们没有帮助。对于后者,数组大小不正确。我不知道它是否真的构建了正确的数组。我得到数组长度:124236,但它应该是 204*203 = 41412 如果您向我展示如何简单地将 Mat openCV 矩阵转换为 C++ 中的普通一维数组,我将不胜感激。
谢谢。
【问题讨论】:
-
您有什么理由将
cv:::Mat to转换为array而不是vector?要执行后面的操作,您可以像这样声明一个向量:std::vector<int> outputVector;并执行outputVector.assign( mat.data, mat.data + mat.total()*mat.channels() );假设您的mat是一个 8 位类型的图像。 -
124,236 = 41,412 * 3。我假设您的输入图像是 RGB。
-
@eldesgraciado,我想用数组构建这段代码并在另一个程序中实现它。如果您能告诉我一种将 Mat 转换为数组的方法,我将不胜感激。