量化:将 0–255 映射为 0–15
每 17 个灰度值映射为一个 4bit 等级(0–15)
inline uint8_t quantize4bit(uint8_t value) {
return value / 17; // 255 / 15 ≈ 17
}
打包:每两个 4bit 像素 → 1 字节
std::shared_ptr<unsigned char> Convert8bitTo4bit(std::shared_ptr<unsigned char>& pixels, int width, int height)
{
size_t pixelCount = width * height;
size_t compressedSize = (pixelCount + 1) / 2; // 每两个像素压缩为1字节
std::shared_ptr<unsigned char> output(new unsigned char[compressedSize], std::default_delete<unsigned char[]>());
for (size_t i = 0; i < compressedSize; ++i) {
uint8_t byte = 0;
size_t idx1 = i * 2;
size_t idx2 = idx1 + 1;
uint8_t high = (idx1 < pixelCount) ? quantize4bit(pixels.get()[idx1]) : 0;
uint8_t low = (idx2 < pixelCount) ? quantize4bit(pixels.get()[idx2]) : 0;
byte = (high << 4) | (low & 0x0F); // 高4位 + 低4位
output.get()[i] = byte;
}
return output;
}
为使的压缩后的图像更平滑增加抖动算法处理
std::shared_ptr<unsigned char> Convert8bitTo4bitFloydSteinberg(std::shared_ptr<unsigned char>& pixels, int width, int height)
{
size_t pixelCount = width * height;
std::vector<uint8_t> temp(pixels.get(), pixels.get() + pixelCount);
int nFactor = 16;
// 抖动扩散
for (int y = 0; y < height; ++y) {
for (int x = 0; x < width; ++x) {
int idx = y * width + x;
uint8_t old = temp[idx];
uint8_t level = old / 17; // 8bit → 4bit 等级(0–15)
uint8_t newVal = level * 17;
temp[idx] = newVal;
int error = static_cast<int>(old) - newVal;
if (x + 1 < width)
temp[idx + 1] = std::clamp(temp[idx + 1] + error * 7 / nFactor, 0, 255);
if (y + 1 < height) {
if (x > 0)
temp[idx + width - 1] = std::clamp(temp[idx + width - 1] + error * 3 / nFactor, 0, 255);
temp[idx + width] = std::clamp(temp[idx + width] + error * 5 / nFactor, 0, 255);
if (x + 1 < width)
temp[idx + width + 1] = std::clamp(temp[idx + width + 1] + error * 1 / nFactor, 0, 255);
}
}
}
// 压缩为 4bit(每2像素 → 1字节)
size_t compressedSize = (pixelCount + 1) / 2;
std::shared_ptr<unsigned char> output(new unsigned char[compressedSize], std::default_delete<unsigned char[]>());
for (size_t i = 0; i < compressedSize; ++i) {
uint8_t byte = 0;
size_t idx1 = i * 2;
size_t idx2 = idx1 + 1;
uint8_t high = (idx1 < pixelCount) ? temp[idx1] / 17 : 0;
uint8_t low = (idx2 < pixelCount) ? temp[idx2] / 17 : 0;
byte = (high << 4) | (low & 0x0F);
output.get()[i] = byte;
}
return output;
}
1677

被折叠的 条评论
为什么被折叠?



