如何从编号的txt文件中读取? (data1.txt,data2.txt等)

时间:2017-05-15 05:12:29

标签: c++

这是我现在正在做的,以便从多个txt文件中读取。什么是更好的方法来处理这个?我想将结果存储在单独的向量中(我在这里调用out1out2等)。 数据包含我正在进行霍夫变换的XY坐标。

ifstream data1, data2, data3, data4;
vector< vector<float> > XY1, XY2, XY3, XY4;
vector<float> row1(2), row2(2), row3(2), row4(2);
vector<CircleData> out1, out2, out3, out4;


// Read data
data1.open("data1.txt");
while (data1 >> row1[0] >> row1[1])
{
    XY1.push_back(row1);
}
data1.close();
// Convert XY-coordinates to pixels with image size as parameter
CoordinatesToImage convert1(XY1, 300);
// Do Hough transformation, then search for the strongest circles in the data 
CircleHough test1;
out1 = test1.houghPeaks(test1.houghTransform(convert1.getScan(), radius), radius, 7);


// Next data file, same procedure
data2.open("data2.txt");
while (data2 >> row2[0] >> row2[1])
{
    XY2.push_back(row2);
}
data2.close();
// Convert XY-coordinates to pixels with image size as parameter
CoordinatesToImage convert2(XY2, 300);
// Do Hough transformation, then search for the strongest circles in the data 
CircleHough test2;
out2 = test2.houghPeaks(test2.houghTransform(convert2.getScan(), radius), radius, 7);


// Next data file, same procedure
data3.open("data3.txt");
......

2 个答案:

答案 0 :(得分:1)

添加方法。

void do_something(std::string file_name){
    ifstream data1{file_name};
    vector< vector<float> > XY;
    while (data1 >> row1[0] >> row1[1])
    {
        XY.push_back(row1);
    }
    data1.close();
    // Convert XY-coordinates to pixels with image size as parameter
    CoordinatesToImage convert1(XY, 300);
    // Do Hough transformation, then search for the strongest circles in the data 
    CircleHough test1;
    out1 = test1.houghPeaks(test1.houghTransform(convert1.getScan(), radius), radius, 7);
}

答案 1 :(得分:0)

对我而言,这似乎是一个典型的代码泛化问题(所以我不会详细介绍这个具体的例子)。可能有很多不同的处理方法,但这可以通过重构现有的代码库来实现。

正如您的代码注释中所指出的,重复代码是负责读取和处理文件输入的部分,因此我建议首先尝试通过在必要时使用变量将该部分写入自己的子例程。例如(返回结果向量):

vector<CircleData> read_and_process_file_input(std::string filename)
{
    // Read data
    ifstream data (filename);
    vector<float> row(2);
    vector<vector<float>> XY;

    while (data >> row[0] >> row[1])
    {
        XY.push_back(row);
    }
    data.close();
    // Convert XY-coordinates to pixels with image size as parameter
    CoordinatesToImage convert1(XY, 300);
    // Do Hough transformation, then search for the strongest circles in the data 
    CircleHough test1;
    return test1.houghPeaks(test1.houghTransform(convert1.getScan(), radius), radius, 7);
}

您可以使用for循环迭代(从1开始索引):

for(int i = 1; i < no_files+1; i++)
    read_and_process_file_input("data" + i + ".txt");

如果您不知道输入文件的数量,或者如果您想避免硬编码,则必须添加存在检查 对于每个新的输入文件。

您希望如何存储结果数据在很大程度上取决于应用程序;您可以使用数据结构来替换变量*。 或者(知道没有输入文件)将它们存储在矩阵中可能更有效(每个输出数据作为列)

相关问题