OpenCV 3.0 - 如何从CSV字符串创建cv :: Mat?

时间:2015-11-25 12:38:50

标签: c++ csv opencv opencv3.0 opencv-mat

我试图从我从python脚本管道输出的CSV字符串创建一个cv :: Mat。我目前正在使用python 2.7,C ++和OpenCV 3.0,而我所能找到的是如何在OpenCV 2.4中实现它,但问题是它与3.0之间的区别很大,而不是以某种方式使用ml :: TrainData 。我不明白它是如何工作的,并且没有示例代码! : - (

我的python脚本的作用是将np.array作为CSV管道,它看起来像这样:

import sys
import numpy as np
import csv


csvToSend = csv.writer(sys.stdout, delimiter=',')

data = np.array([ [3, 7, 9],
               [1, 7, 0],
               [4, 12, 8]])

csvToSend.writerows(data)

python脚本目前正在模拟以bgr RAW格式发送图片的相机。

管道数据由我的C ++代码接收,这就是代码目前的样子:

#include <iostream>
#include <string>
#include <opencv2/core/core.hpp>

using namespace std;
using namespace cv;

string values = "", csvPart;
Mat img;
int i;

int main()
{
    for (i = 0; i < 3; i++)
    {

        cin >> csvPart; //here I get my CSV lines from python-script

        if (values == "") values = values + csvPart;

        else values = values + "\n" + csvPart;  //makes the CVS lines look like a 3x3 matrix again
    }

    cout << values << endl; //prints the CVS to see that it looks like it did before piping it over to the C++ code

    /* how the printed string looks like
    3,7,9 
    1,7,0
    4,12,8    */

/*      Here I want to load the "values" into the Mat img
        so I can do my mojo with openCV in C++          */
}

如果有人能帮我解决这个问题并给我一个简单的代码示例,我将不胜感激。 如果有更好的方法将np.array传递给C ++代码并将其加载到cv :: Mat中,我的手臂就会为你敞开! ; - )

1 个答案:

答案 0 :(得分:6)

csv文件的每一行代表一行。如果您的图像是1个通道,则每个值都是像素的灰度值:

1,2,3 
4,5,6 
7,8,9 

得到的3x3 1通道图像是:

enter image description here

如果您的图像是3通道,则每行中的3个连续值表示 bgr 三元组。例如:

1,2,3,200,100,200
4,5,6,47,205,103
7,8,9,95,23,209

产生3x2 3通道图像:

enter image description here

loadFromCSV函数接受csv内容的字符串和OpenCV图像类型,并返回图像:

Mat loadFromCSV(const string& values, int opencv_type);

看看完整的代码:

#include <opencv2\opencv.hpp>
#include <string>
#include <sstream>
#include <iostream>
using namespace std;
using namespace cv;

Mat loadFromCSV(const string& values, int opencv_type)
{
    Mat m;

    stringstream ss(values);
    string line;
    while (getline(ss, line))
    {
        vector<double> dvals;

        stringstream ssline(line);
        string val;
        while (getline(ssline, val, ','))
        {
            dvals.push_back(stod(val));
        }

        Mat mline(dvals, true);
        transpose(mline, mline);

        m.push_back(mline);
    }

    int ch = CV_MAT_CN(opencv_type);

    m = m.reshape(ch);
    m.convertTo(m, opencv_type);
    return m;
}

int main()
{
    string values = "1,2,3\n4,5,6\n7,8,9";
    Mat img = loadFromCSV(values, CV_8UC1);
    //Mat img = loadFromCSV(values, CV_8UC3);

    //string values = "1,2,3,200,100,200\n4,5,6,47,205,103\n7,8,9,95,23,209";
    //Mat img = loadFromCSV(values, CV_8UC3);

    cout << "Img:" << endl;
    cout << img << endl;

    imshow("Img", img);
    waitKey();

    return 0;
}