回答編集履歴
1
a
answer
CHANGED
@@ -1,6 +1,6 @@
|
|
1
1
|
以下の手順でテキストファイルをバイナリ形式で保存できます。
|
2
2
|
|
3
|
-
## 手順
|
3
|
+
## 手順 (Python)
|
4
4
|
|
5
5
|
1. numpy.loadtxt() でテキストファイルを読み込み。
|
6
6
|
2. ndarray.tofile() でバイナリ形式で保存する。(row-major-order)
|
@@ -28,4 +28,76 @@
|
|
28
28
|
d = f.read()
|
29
29
|
print('bytes of data.binary', len(d)) # bytes of data.binary 20000
|
30
30
|
# Python の float 型は 8bytes (倍精度) なので、4 * 50 * 50 = 20000
|
31
|
+
```
|
32
|
+
|
33
|
+
## C++
|
34
|
+
|
35
|
+
すいません。タイトルを見てませんでした。
|
36
|
+
「画像処理ソフトの入力データを作る」が目的であれば、言語はなんでもよいと思いますが、C++ のサンプルコードも貼っておきますね。
|
37
|
+
(C言語は面倒なので、省略します。すいません。)
|
38
|
+
|
39
|
+
```cpp
|
40
|
+
#include <fstream>
|
41
|
+
#include <iostream>
|
42
|
+
#include <sstream>
|
43
|
+
#include <string>
|
44
|
+
#include <vector>
|
45
|
+
|
46
|
+
/**
|
47
|
+
* @brief 指定したパスからデータを読み込む。
|
48
|
+
* @param filepath ファイルパス
|
49
|
+
* @param data 読み込んだデータ
|
50
|
+
*/
|
51
|
+
void readTxtData(
|
52
|
+
const std::string &filepath, std::vector<std::vector<double>> &data)
|
53
|
+
{
|
54
|
+
data.clear();
|
55
|
+
std::ifstream ifs(filepath);
|
56
|
+
|
57
|
+
std::string line;
|
58
|
+
while (std::getline(ifs, line)) {
|
59
|
+
if (line.empty())
|
60
|
+
continue;
|
61
|
+
std::vector<double> rowData;
|
62
|
+
std::stringstream lineStream(line);
|
63
|
+
|
64
|
+
double value;
|
65
|
+
while (lineStream >> value) {
|
66
|
+
rowData.push_back(value);
|
67
|
+
}
|
68
|
+
|
69
|
+
data.push_back(rowData);
|
70
|
+
}
|
71
|
+
}
|
72
|
+
|
73
|
+
/**
|
74
|
+
* @brief 指定したパスにデータを書き込む。
|
75
|
+
* @param filepath ファイルパス
|
76
|
+
* @param data 読み込んだデータ
|
77
|
+
*/
|
78
|
+
void writeData(
|
79
|
+
const std::string &filepath, const std::vector<std::vector<double>> &data)
|
80
|
+
{
|
81
|
+
std::ofstream ofs(filepath, std::ios::out | std::ios::binary);
|
82
|
+
for (const auto &rowData : data) {
|
83
|
+
for (const auto &v : rowData)
|
84
|
+
ofs.write(reinterpret_cast<const char *>(&v), sizeof(v));
|
85
|
+
}
|
86
|
+
}
|
87
|
+
|
88
|
+
int main()
|
89
|
+
{
|
90
|
+
// データを読み込む。
|
91
|
+
std::vector<std::vector<double>> data;
|
92
|
+
readTxtData("data.csv", data);
|
93
|
+
|
94
|
+
// データを表示する。
|
95
|
+
for (const auto &rowData : data) {
|
96
|
+
for (const auto &v : rowData)
|
97
|
+
std::cout << v << " ";
|
98
|
+
std::cout << std::endl;
|
99
|
+
}
|
100
|
+
|
101
|
+
writeData("data.binary", data);
|
102
|
+
}
|
31
103
|
```
|