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

量化:将 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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值