問題:
有沒有一種好方法可以將大小為 (9000,9000,4) 的 3D 浮點向量寫入 C 中的輸出檔案?
我的 C 程式生成一個 9000x9000 的影像矩陣,每個像素有 4 個顏色值(R、G、B、A)。我需要將此資料保存為輸出檔案,以便以后使用 python 讀入 numpy.array() (或類似的)。每個顏色值都保存為一個浮點數(可以大于 1.0),它將在代碼的 python 部分中進行規范化。
目前,我正在將 (9000,9000,4) 大小的向量寫入一個包含 8100 萬行和 4 列的 CSV 檔案。這對于讀寫來說很慢,并且會創建大檔案(~650MB)。
NOTE: I run the program multiple times (up to 20) for each trial, so read/write times and file sizes add up.
當前的 C 代碼:
這是初始化和寫入 3D 矢量的片段。
// initializes the vector with data from 'makematrix' class instance
vector<vector<vector<float>>> colorMat = makematrix->getMatrix();
outfile.open("../output/11_14MidRed9k8.csv",std::ios::out);
if (outfile.is_open()) {
outfile << "r,g,b,a\n"; // writes column labels
for (unsigned int l=0; l<colorMat.size(); l ) { // 0 to 8999
for (unsigned int m=0; m<colorMat[0].size(); m ) { // 0 to 8999
outfile << colorMat[l][m][0] << ',' << colorMat[l][m][1] << ','
<< colorMat[l][m][2] << ',' << colorMat[l][m][3] << '\n';
}
}
}
outfile.close();
概括:
我愿意更改輸出檔案型別、我使用的資料結構或任何其他可以提高效率的東西。歡迎任何和所有建議!
uj5u.com熱心網友回復:
使用舊的 C 檔案函式和二進制格式
auto startT = chrono::high_resolution_clock::now();
ofstream outfile;
FILE* f = fopen("example.bin", "wb");
if (f) {
const int imgWidth = 9000;
const int imgHeight = 9000;
fwrite(&imgWidth, sizeof(imgWidth), 1, f);
fwrite(&imgHeight, sizeof(imgHeight), 1, f);
for (unsigned int i=0; i<colorMat.size(); i)
{
fwrite(&colorMat[i], sizeof(struct Pixel), 1, f);
}
}
auto endT = chrono::high_resolution_clock::now();
cout << "Time taken : " << chrono::duration_cast<chrono::seconds>(endT-startT).count() << endl;
fclose(f);
格式如下:
[ImageWidth][ImageHeight][RGBA][RGBA[RGBA] ... 適用于所有 ImageWidth * ImageHeight 像素。
您的樣本在我的機器上運行了 119 秒。此代碼在 2 秒內運行。
但請注意,無論如何該檔案都會很大:您正在撰寫相當于兩個 8K 檔案而沒有任何壓縮的檔案。
除此之外,關于您的代碼的一些提示:
- 不要使用浮點向量來表示您的像素。它們不會有比 RGBA 更多的組件。而是創建一個帶有四個浮點數的簡單結構。
- 您不需要分別查看寬度和高度。在內部,所有行一個接一個地依次放置。創建寬度 * 高度大小的一維陣列更容易。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/525993.html
上一篇:GoogleSheetsAppsScriptWebApp中csv中的額外雙引號
下一篇:Python將字典匯出為CSV
