图像压缩-将8bit数据压缩为1bit

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;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值