在C ++中将像素数据转换为图像

时间:2015-07-14 17:07:09

标签: c++ image file-io

我有一个程序可以生成具有以下结构的8位图像:

struct int8image
{
  int width;
  int height;
  unsigned char* image;
};

将像素数据(int8image.image)转储到文本文件后,我得到了这个输出:

0605 0606 0606 0605 0606 0506 0606 0606
0606 0605 0606 0506 0606 0606 0606 0606
0606 0606 0606 0606 0606 0505 0606 0706
0606 0606 0606 0606 0606 0606 0706 0706
.....

我如何将其转换为可查看的图像(格式无关紧要)?

4 个答案:

答案 0 :(得分:1)

您可以在命令行使用ImageMagick转换图像。它安装在大多数Linux发行版上,可用于OS X(最好通过homebrew)和Windows。

如果要将其转换为PNG,可以运行:

convert -size 1392x1040 -depth 8 image.gray -auto-level image.png

enter image description here

你的图像对比度非常低,所以我添加了-auto-level来拉伸它。你的图像是灰度的。

您还可以使用ImageMagick C ++库here实现相同的处理。

答案 1 :(得分:0)

我会使用OpenCV。您可以使用宽度和高度作为尺寸将结构转换为cv :: Mat。然后你可以使用OpenCV函数来查看图像或相当容易地写出bmp,png,tiff或jpg。鉴于你有未签名的char数据,我认为它已经是8位灰度,所以它看起来像这样。

int8image testData;

// Do stuff in your program so that testData contains an image.

// Define a cv::Mat object with a pointer to the data and the data type set
// as "CV_8U" which means 8-bit unsigned data
cv::Mat image( testData.height, testData.width, CV_8U, testData.image );

// Write the image to a bitmap in the current working directory named 
// "test.bmp". This is just an example of one way you could write it out.
cv::imwrite( "test.bmp", image );

答案 2 :(得分:0)

库是最灵活的,但是如果你正在寻找快速和脏的,你可以为RGB24写出一个简单的54字节BMP头,并假设你的数据是灰度级的,只需重复3个中的每一个的八位字节。每个像素的组成部分。或者,如果您希望能够更直接地写入图像数据,请为托盘化图像编写BMP标题,并且托盘基本上是256条目灰度(000000,010101,020202 ... ffffff)。如果你查看BMP标题格式,这两种方式都非常简单。

答案 3 :(得分:0)

另一种选择是使用LodePNG library,它很容易设置,因为它没有依赖关系,你可以简单地将源文件放入你的项目并使用它进行编译。它非常易于使用,并允许您将数据保存到丢失的PNG图像中。