酷代码 AI
菜单
服务商

256级灰阶图像压缩为16级灰阶的C++实现方案

以下是实现该功能的 C++ 代码: ```cpp #include <iostream> #include <vector> #include <algorithm> #include <string> #include <cmath> // 定义一个结构体来存储灰阶和其对应的出现次数 struct GrayLevel { int level; int count; GrayLevel(int l, int c) : level(l), count(c) {} // 重载比较运算符,用于排序 bool operator<(const GrayLevel& other) const { if (count != other.count) { return count > other.count; } return level < other.level; } }; // 将十六进制字符串转换为十进制整数 int hexToDec(const std::string& hex) { int result = 0; for (char c : hex) { if (c >= '0' && c <= '9') { result = result * 16 + (c - '0'); } else { result = result * 16 + (c - 'A' + 10); } } return result; } // 将十进制整数转换为十六进制字符 char decToHex(int dec) { if (dec >= 0 && dec <= 9) { return '0' + dec; } return 'A' + (dec - 10); } int main() { int n; std::cin >> n; // 统计每种灰阶的数量 std::vector<int> grayCount(256, 0); std::vector<std::string> image(n); for (int i = 0; i < n; ++i) { std::cin >> image[i]; for (size_t j = 0; j < image[i].length(); j += 2) { std::string hex = image[i].substr(j, 2); int level = hexToDec(hex); ++grayCount[level]; } } // 找出数量最多的前 16 种灰阶 std::vector<GrayLevel> grayLevels; for (int i = 0; i < 256; ++i) { if (grayCount[i] > 0) { grayLevels.emplace_back(i, grayCount[i]); } } std::sort(grayLevels.begin(), grayLevels.end()); std::vector<int> selectedLevels(16); for (int i = 0; i < 16; ++i) { selectedLevels[i] = grayLevels[i].level; } // 输出选定的 16 种灰阶的十六进制编码 for (int level : selectedLevels) { std::cout << decToHex(level / 16) << decToHex(level % 16); } std::cout << std::endl; // 压缩图像 for (const std::string& row : image) { for (size_t j = 0; j < row.length(); j += 2) { std::string hex = row.substr(j, 2); int level = hexToDec(hex); int minDiff = 256; int closestIndex = 0; for (int i = 0; i < 16; ++i) { int diff = std::abs(level - selectedLevels[i]); if (diff < minDiff) { minDiff = diff; closestIndex = i; } } std::cout << decToHex(closestIndex); } std::cout << std::endl; } return 0; } ``` ### 代码解释: 1. **结构体 `GrayLevel`**:用于存储灰阶和其对应的出现次数,同时重载了比较运算符,以便对灰阶进行排序。 2. **函数 `hexToDec`**:将十六进制字符串转换为十进制整数。 3. **函数 `decToHex`**:将十进制整数转换为十六进制字符。 4. **主函数 `main`**: - 读取输入的行数 `n`。 - 统计每种灰阶的数量。 - 找出数量最多的前 16 种灰阶。 - 输出选定的 16 种灰阶的十六进制编码。 - 压缩图像,将每个像素转换为最近的 16 种灰阶之一,并输出压缩后的图像。 ######[AI问答 | 1080点数解答 | 2026-02-14 20:19:02]

相关提问
发财导航,免费问AI
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]