std::shared_ptr<unsigned char> Convert8bitTo1bit(std::shared_ptr<unsigned char>& pixels, int width, int height)
{
size_t pixelCount = width * height;
size_t compressedSize = (pixelCount + 7) / 8;
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 < 8; ++j) {
size_t idx = i * 8 + j;
if (idx < pixelCount) {
unsigned char value = pixels.get()[idx];
unsigned char bit = (value >= 128) ? 1 : 0;
byte |= (bit << (7 - j)); // 高位优先
}
}
output.get()[i] = byte;
}
return output;
}
为使的压缩后的图像更平滑增加抖动算法处理
std::shared_ptr<unsigned char> Convert8bitTo1bitFloydSteinberg(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 newVal = (old >= 128) ? 255 : 0;
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);
}
}
}
// 压缩为 1bit(每8像素 → 1字节)
size_t compressedSize = (pixelCount + 7) / 8;
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;
for (size_t j = 0; j < 8; ++j) {
size_t idx = i * 8 + j;
uint8_t bit = (idx < pixelCount && temp[idx] >= 128) ? 1 : 0;
byte |= (bit << (7 - j));
}
output.get()[i] = byte;
}
return output;
}
5144

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



