1、题目:简单图像压缩 描述: 你正在开发一个基础的图像压缩算法。给定一个表示灰度图像的二维整数矩阵,中每个像素的灰度值范围 是0-255。你的任务是实现一个简单的压缩算法,将相邻的相同值像素组合在一起,以减少存储空间。 要求:
实现函数vector <vector < pair <int, int>> > compresslmage(const vector<vector<int> > & image)
输入参数image是一个示灰度图像的二维整数矩阵 返回值应该是一个压缩后的数据结构,其中每个元素是一个pair<int, int>,示(像素值,连续出现的次数) 压缩应该在每一行内进行,不跨行压缩 考虑输入为空或只有-行/-列的情况 优化算法以处理大型图像(如4K分辨率)
示例:
输入:
[
[1, 1, 2, 2, 2],
[3, 3, 3, 4, 4],
[5, 5, 5, 5, 5]
]
输出:
[
[[1, 2], [2, 3]],
[[3, 3], [4, 2]],
[[5, 5]]
]
#include <vector>
#include <utility> // for std::pair
#include<iostream>
using namespace std;
vector<vector<pair<int, int>>> compressImage(const vector<vector<int>>& image) {
vector<vector<pair<int, int>>> compressed;
// 检查输入是否为空
if (image.empty()) return compressed;
// 遍历每一行
for (const auto& row : image) {
vector<pair<int, int>> currentRow;
if (row.empty()) {
// 如果当前行为空,则添加一个空的压缩结果
compressed.push_back(currentRow);
continue;
}
int currentValue = row[0];
int count = 1;
// 遍历当前行的每个像素
for (size_t i = 1; i < row.size(); ++i) {
if (row[i] == currentValue) {
// 如果当前像素与前一个像素相同,则增加计数
++count;
}
else {
// 如果不同,则将当前值和计数添加到结果中,并重置计数器和当前值
currentRow.push_back(make_pair(currentValue, count));
currentValue = row[i];
count = 1;
}
}
// 将最后一组值和计数添加到结果中
currentRow.push_back(make_pair(currentValue, count));
compressed.push_back(currentRow);
}
return compressed;
}
int main() {
vector<vector<int>> image = {
{1, 1, 2, 2, 2},
{3, 3, 3, 4, 4},
{5, 5, 5, 5, 5}
};
vector<vector<pair<int, int>>> compressedImage = compressImage(image);
// 打印结果
for (const auto& row : compressedImage) {
for (const auto& pair : row) {
cout << "[" << pair.first << ", " << pair.second << "] ";
}
cout << endl;
}
return 0;
}