以下の手順でテキストファイルをバイナリ形式で保存できます。
手順 (Python)
- numpy.loadtxt() でテキストファイルを読み込み。
- ndarray.tofile() でバイナリ形式で保存する。(row-major-order)
サンプルコード
50行50列の数値データが書き込まれた CSV ファイルを読み込み、バイナリ形式で保存します。(row-major-order)
python
1import numpy as np
2
3# テスト用データ作成 (50行50列でスペース区切り)
4data = np.random.randn(50, 50)
5np.savetxt('data.csv', array, delimiter=' ')
6
7# ファイルを読み込む。
8data = np.loadtxt('data.csv')
9print(data.shape, data.dtype) # (50, 50) float64
10
11# バイナリ形式で保存 row-major-order で書き込まれます。
12data.tofile('data.binary')
13
14# バイナリ形式で保存できたか、確認する。
15with open('data.binary', 'rb') as f:
16 d = f.read()
17 print('bytes of data.binary', len(d)) # bytes of data.binary 20000
18 # Python の float 型は 8bytes (倍精度) なので、4 * 50 * 50 = 20000
C++
すいません。タイトルを見てませんでした。
「画像処理ソフトの入力データを作る」が目的であれば、言語はなんでもよいと思いますが、C++ のサンプルコードも貼っておきますね。
(C言語は面倒なので、省略します。すいません。)
cpp
1#include <fstream>
2#include <iostream>
3#include <sstream>
4#include <string>
5#include <vector>
6
7/**
8 * @brief 指定したパスからデータを読み込む。
9 * @param filepath ファイルパス
10 * @param data 読み込んだデータ
11 */
12void readTxtData(
13 const std::string &filepath, std::vector<std::vector<double>> &data)
14{
15 data.clear();
16 std::ifstream ifs(filepath);
17
18 std::string line;
19 while (std::getline(ifs, line)) {
20 if (line.empty())
21 continue;
22 std::vector<double> rowData;
23 std::stringstream lineStream(line);
24
25 double value;
26 while (lineStream >> value) {
27 rowData.push_back(value);
28 }
29
30 data.push_back(rowData);
31 }
32}
33
34/**
35 * @brief 指定したパスにデータを書き込む。
36 * @param filepath ファイルパス
37 * @param data 読み込んだデータ
38 */
39void writeData(
40 const std::string &filepath, const std::vector<std::vector<double>> &data)
41{
42 std::ofstream ofs(filepath, std::ios::out | std::ios::binary);
43 for (const auto &rowData : data) {
44 for (const auto &v : rowData)
45 ofs.write(reinterpret_cast<const char *>(&v), sizeof(v));
46 }
47}
48
49int main()
50{
51 // データを読み込む。
52 std::vector<std::vector<double>> data;
53 readTxtData("data.csv", data);
54
55 // データを表示する。
56 for (const auto &rowData : data) {
57 for (const auto &v : rowData)
58 std::cout << v << " ";
59 std::cout << std::endl;
60 }
61
62 writeData("data.binary", data);
63}