图像压缩-将8bit数据压缩为2bit
std::shared_ptr<unsigned char> Convert8bitTo2bit(std::shared_ptr<unsigned char>& pixels, int width, int height)
{size_t pixelCount = width * height;size_t compressedSize = (pixelCount + 3) / 4; // 每4个像素压缩为1字节std::shared_ptr<unsigned char> output(new unsigned char[compressedSize], std::default_delete<unsigned char[]>());for (size_t i = 0; i < compressedSize; ++i) {unsigned char byte = 0;for (size_t j = 0; j < 4; ++j) {size_t idx = i * 4 + j;unsigned char level = 0;if (idx < pixelCount) {unsigned char value = pixels.get()[idx];level = value / 64; // 8bit → 2bit(0–3)}byte |= (level & 0x03) << (6 - j * 2); // 高位优先排列}output.get()[i] = byte;}return output;
}
为使的压缩后的图像更平滑增加抖动算法处理
uint8_t quantize2bit(uint8_t value) {return value / 64; // 0~255 → 0~3
}uint8_t levelToGray(uint8_t level) {return level * 85; // 0→0, 1→85, 2→170, 3→255
}std::shared_ptr<unsigned char> Convert8bitTo2bitFloydSteinberg(std::shared_ptr<unsigned char>& pixels, int width, int height)
{int totalPixels = width * height;std::vector<uint8_t> temp(pixels.get(), pixels.get() + totalPixels);// Floyd–Steinberg 抖动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 = quantize2bit(old);uint8_t newVal = levelToGray(level);temp[idx] = newVal;int error = static_cast<int>(old) - newVal;// 扩散误差if (x + 1 < width)temp[idx + 1] = clamp(temp[idx + 1] + error * 7 / nFactor, 0, 255); //向右扩散if (y + 1 < height) {if (x > 0)temp[idx + width - 1] = clamp(temp[idx + width - 1] + error * 3 / nFactor, 0, 255); //左下扩散temp[idx + width] = clamp(temp[idx + width] + error * 5 / nFactor, 0, 255); //向下扩散if (x + 1 < width)temp[idx + width + 1] = clamp(temp[idx + width + 1] + error * 1 / nFactor, 0, 255); //右下扩散}}}// 压缩为 2bit 数据(每 4 像素 → 1 字节)int compressedSize = (totalPixels + 3) / 4;std::shared_ptr<unsigned char> pixels2bit(new unsigned char[compressedSize], std::default_delete<unsigned char[]>());for (int i = 0; i < compressedSize; ++i) {uint8_t byte = 0;for (int j = 0; j < 4; ++j) {int idx = i * 4 + j;uint8_t level = (idx < totalPixels) ? quantize2bit(temp[idx]) : 0;byte |= (level & 0x03) << (6 - j * 2);}pixels2bit.get()[i] = byte;}return pixels2bit;
}
