我现有灰度数据,16位。想生成png格式的灰度图。我调用了lodepng_encode_file函数,后两位参数写的是LCT_GREY,16但是生成的却是8位的png。这里确实搞不懂为什么?因为这个函数的像素是char嘛? 那这个函数需要的像素/灰度值参数到底是什么类型呢?
希望有朋友帮助解答一下!
从这个函数的定义看,buffer就是uchar的,所以怎么可能直接保存ushort?除非重排了,将16拆成2个8
unsigned lodepng_encode_file(const char* filename, const unsigned char* image, unsigned w, unsigned h,
LodePNGColorType colortype, unsigned bitdepth) {
unsigned char* buffer;
size_t buffersize;
unsigned error = lodepng_encode_memory(&buffer, &buffersize, image, w, h, colortype, bitdepth);
if(!error) error = lodepng_save_file(buffer, buffersize, filename);
lodepng_free(buffer);
return error;
}
如果是这样,得你看函数底层的实现了。
不知道你这个问题是否已经解决, 如果还没有解决的话:答案:
根据lodepng的文档,能够支持16位的像素类型是LCT_GREY_ALPHA_16和LCT_RGBA_16类型,不支持LCT_GREY16类型。但是可以通过改变将数据存储在PNG图像中的方式来解决该问题。具体地,将16位的灰度值用两个8位的值表示,再将它们存储在PNG图像的RGB通道中。存储的时候需要按照大端方式存储。以下是一个使用lodepng的示例代码:
#include "lodepng.h"
#include <vector>
#include <iostream>
int main(int argc, char* argv[])
{
// Assumes that the 16-bit grayscale data is stored in an array named data16 with width, height, and pitch defined.
int width = 1024;
int height = 1024;
size_t pitch = width * sizeof(unsigned short);
std::vector<unsigned char> data8(width * height * 2); // 2 bytes per pixel
// Convert 16-bit grayscale data to 8-bit grayscale data
for (size_t y = 0; y < height; y++)
{
unsigned short* row16 = (unsigned short*)(data16 + y * pitch);
for (size_t x = 0; x < width; x++)
{
unsigned char pixel[2];
pixel[0] = (row16[x] >> 8) & 0xff; // high byte
pixel[1] = row16[x] & 0xff; // low byte
data8[y * width * 2 + x * 2] = pixel[0];
data8[y * width * 2 + x * 2 + 1] = pixel[1];
}
}
// Encode the 8-bit grayscale data into a PNG file
std::vector<unsigned char> png;
unsigned error = lodepng::encode(png, data8, width, height, LCT_RGB, 16);
if (error) std::cerr << "Failed to encode PNG file: " << lodepng_error_text(error) << std::endl;
else lodepng::save_file(png, "output.png");
return 0;
}
这个示例代码将16位的灰度数据(data16)转换成8位的数据(data8),并将8位的数据使用lodepng函数编码成PNG图像。在编码时使用LCT_RGB参数来表示像素类型,16表示位深度。编码完成后,可以将PNG图像保存到磁盘中。