gpt4 book ai didi

c++ - Targa 运行长度编码

转载 作者:行者123 更新时间:2023-11-28 05:12:15 25 4
gpt4 key购买 nike

我目前正在尝试解压缩 targa (RGB24_RLE) 图像数据。

我的算法是这样的:

static constexpr size_t kPacketHeaderSize = sizeof(char);

//http://paulbourke.net/dataformats/tga/
inline void DecompressRLE(unsigned int a_BytePerPixel, std::vector<CrByte>& a_In, std::vector<CrByte>& a_Out)
{
for (auto it = a_In.begin(); it != a_In.end();)
{
//Read packet header
int header = *it & 0xFF;
int count = (header & 0x7F) + 1;

if ((header & 0x80) != 0) //packet type
{
//For the run length packet, the header is followed by
//a single color value, which is assumed to be repeated
//the number of times specified in the header.

auto paStart = it + kPacketHeaderSize;
auto paEnd = paStart + a_BytePerPixel;

//Insert packets into output buffer
for (size_t pk = 0; pk < count; ++pk)
{
a_Out.insert(a_Out.end(), paStart, paEnd);
}

//Jump to next header
std::advance(it, kPacketHeaderSize + a_BytePerPixel);
}
else
{
//For the raw packet, the header s followed by
//the number of color values specified in the header.

auto paStart = it + kPacketHeaderSize;
auto paEnd = paStart + count * a_BytePerPixel;

//Insert packets into output buffer
a_Out.insert(a_Out.end(), paStart, paEnd);

//Jump to next header
std::advance(it, kPacketHeaderSize + count * a_BytePerPixel);
}
}
}

这里调用:

//Read compressed data
std::vector<CrByte> compressed(imageSize);
ifs.seekg(sizeof(Header), std::ifstream::beg);
ifs.read(reinterpret_cast<char*>(compressed.data()), imageSize);

//Decompress
std::vector<CrByte> decompressed(imageSize);
DecompressRLE(bytePerPixel, compressed, decompressed);

imageSize 定义如下:

size_t imageSize = hd.width * hd.height * bytePerPixel

但是,在 DecompressRLE() 完成后(对于 2048x2048 纹理,这需要很长时间)解压缩仍然是空的/仅包含零。也许我错过了一些东西。

count 有时似乎高得不合理,我认为这是不正常的。compressedSize 应该 小于 imageSize,否则不会被压缩。但是,使用 ifstream::tellg() 给我错误的结果。有帮助吗?

最佳答案

如果您仔细查看调试器中的变量,您会看到 std::vector<CrByte> decompressed(imageSize);imageSize 声明一个 vector 其中的元素。在 DecompressRLE然后在该 vector 的末尾插入,使其增长。这就是为什么您的解压缩图像充满零,也是为什么需要这么长时间(因为 vector 会定期调整大小)。

你要做的是预留空间:

std::vector<CrByte> decompressed;
decompressed.reserve(imageSize);

您的压缩缓冲区看起来比文件内容大,因此您仍在解压缩文件末尾。压缩后的文件大小应该在Header .使用它。

关于c++ - Targa 运行长度编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43282492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com