灰度图像稀疏矩阵压缩实例代码
时间: 2024-05-16 13:10:11 浏览: 122
灰度图像的稀疏矩阵压缩可以使用三元组存储法来实现。下面是一个简单的例子代码:
```cpp
#include <iostream>
#include <vector>
using namespace std;
// 稀疏矩阵压缩
void compress(vector<vector<int>>& matrix, vector<vector<int>>& compressed) {
int rows = matrix.size();
int cols = matrix.size();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (matrix[i][j] != 0) {
vector<int> temp;
temp.push_back(i);
temp.push_back(j);
temp.push_back(matrix[i][j]);
compressed.push_back(temp);
}
}
}
}
// 打印压缩后的矩阵
void printCompressed(vector<vector<int>>& compressed) {
int len = compressed.size();
for (int i = 0; i < len; i++) {
cout << compressed[i] << " " << compressed[i] << " " << compressed[i] << endl;
}
}
int main() {
vector<vector<int>> matrix = {{0, 0, 3, 0},
{0, 4, 0, 6},
{7, 0, 0, 0},
{0, 0, 9, 0}};
vector<vector<int>> compressed;
compress(matrix, compressed);
printCompressed(compressed);
return 0;
}
```
这个例子中,`compress()`函数将原始的稀疏矩阵压缩成三元组存储在`compressed`中,`printCompressed()`函数打印出压缩后的矩阵。你可以根据自己的需要对代码进行修改。
阅读全文